Python中的哈希图


144

我想在Python中实现HashMap。我想请用户输入。根据他的输入,我正在从HashMap中检索一些信息。如果用户输入HashMap的键,我想检索相应的值。

如何在Python中实现此功能?

HashMap<String,String> streetno=new HashMap<String,String>();
   streetno.put("1", "Sachin Tendulkar");
   streetno.put("2", "Dravid");
   streetno.put("3","Sehwag");
   streetno.put("4","Laxman");
   streetno.put("5","Kohli")

Answers:


246

Python字典是一种内置类型,支持键值对。

streetno = {"1": "Sachin Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli"}

以及使用dict关键字:

streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) 

要么:

streetno = {}
streetno["1"] = "Sachin Tendulkar" 

11
第二个示例只是以与以前相同的方式构建了一个字典,然后将其复制。dict在这种情况下,另一种用法更为合适,dict(key1=value1, key2=value2, ...)但它需要字符串的键,这些键也是有效的Python标识符(并且在内部,这还会创建一个字典)。

有趣的是,我没有意识到裸露的字符串是有效的标识符。
艾伦(Alan)

我不确定我是否正确理解了(什么是“裸字符串”?),但我相信您对此有所了解。您更新的第二个示例无效,我从不打算陈述类似的内容。的关键字参数的语法,它接受裸标识符,在内部使用的字典。该dict构造支持关键字参数和喜欢的作品def dict(**kwds): return kwds,如果给定的关键字参数。

第二个示例引发语法错误。变量名不能以数字开头
Simon Bergot 2012年

是的,它看起来像一个“地图”,它的作用就像一个“地图”。但是问题不是“ Python中的Map”,而是“ Python中的Hash Map”:字典是hash(!)地图吗?
309963d8521805330a44bdcb3d87f3


24

它是Python内置的。参见字典

根据您的示例:

streetno = {"1": "Sachine Tendulkar",
            "2": "Dravid",
            "3": "Sehwag",
            "4": "Laxman",
            "5": "Kohli" }

然后,您可以像这样访问它:

sachine = streetno["1"]

还值得一提:它可以使用任何非可变数据类型作为键。也就是说,它可以使用元组,布尔值或字符串作为键。


16
streetno = { 1 : "Sachin Tendulkar",
            2 : "Dravid",
            3 : "Sehwag",
            4 : "Laxman",
            5 : "Kohli" }

并获取值:

name = streetno.get(3, "default value")

要么

name = streetno[3]

那就是使用数字作为键,在数字两边加上引号以使用字符串作为键。


14

哈希图是Python内置的,它们称为字典

streetno = {}                        #create a dictionary called streetno
streetno["1"] = "Sachin Tendulkar"   #assign value to key "1"

用法:

"1" in streetno                      #check if key "1" is in streetno
streetno["1"]                        #get the value from key "1"

请参阅文档以获取更多信息,例如内置方法等。它们很棒,并且在Python程序中非常常见(毫不奇怪)。


12

这是使用python实现的Hash Map的实现。为简单起见,Hash Map的大小固定为16。可以轻松更改。重新哈希不在此代码范围内。

class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.next = None

class HashMap:
    def __init__(self):
        self.store = [None for _ in range(16)]
    def get(self, key):
        index = hash(key) & 15
        if self.store[index] is None:
            return None
        n = self.store[index]
        while True:
            if n.key == key:
                return n.value
            else:
                if n.next:
                    n = n.next
                else:
                    return None
    def put(self, key, value):
        nd = Node(key, value)
        index = hash(key) & 15
        n = self.store[index]
        if n is None:
            self.store[index] = nd
        else:
            if n.key == key:
                n.value = value
            else:
                while n.next:
                    if n.key == key:
                        n.value = value
                        return
                    else:
                        n = n.next
                n.next = nd

hm = HashMap()
hm.put("1", "sachin")
hm.put("2", "sehwag")
hm.put("3", "ganguly")
hm.put("4", "srinath")
hm.put("5", "kumble")
hm.put("6", "dhoni")
hm.put("7", "kohli")
hm.put("8", "pandya")
hm.put("9", "rohit")
hm.put("10", "dhawan")
hm.put("11", "shastri")
hm.put("12", "manjarekar")
hm.put("13", "gupta")
hm.put("14", "agarkar")
hm.put("15", "nehra")
hm.put("16", "gawaskar")
hm.put("17", "vengsarkar")
print(hm.get("1"))
print(hm.get("2"))
print(hm.get("3"))
print(hm.get("4"))
print(hm.get("5"))
print(hm.get("6"))
print(hm.get("7"))
print(hm.get("8"))
print(hm.get("9"))
print(hm.get("10"))
print(hm.get("11"))
print(hm.get("12"))
print(hm.get("13"))
print(hm.get("14"))
print(hm.get("15"))
print(hm.get("16"))
print(hm.get("17"))

输出:

sachin
sehwag
ganguly
srinath
kumble
dhoni
kohli
pandya
rohit
dhawan
shastri
manjarekar
gupta
agarkar
nehra
gawaskar
vengsarkar

我认为您的逻辑部分正确!hash(key) & 15,,73%15= 13但等价:1001001 & 0001111 = 00011119不是13,我认为使用mod是正确的操作。如果我错了,请纠正我!
阿努

不过,您如何遍历列表?
Petro的

8
class HashMap:
    def __init__(self):
        self.size = 64
        self.map = [None] * self.size

    def _get_hash(self, key):
        hash = 0

        for char in str(key):
            hash += ord(char)
        return hash % self.size

    def add(self, key, value):
        key_hash = self._get_hash(key)
        key_value = [key, value]

        if self.map[key_hash] is None:
            self.map[key_hash] = list([key_value])
            return True
        else:
            for pair in self.map[key_hash]:
                if pair[0] == key:
                    pair[1] = value
                    return True
                else:
                    self.map[key_hash].append(list([key_value]))
                    return True

    def get(self, key):
        key_hash = self._get_hash(key)
        if self.map[key_hash] is not None:
            for pair in self.map[key_hash]: 
                if pair[0] == key:
                    return pair[1]
        return None

    def delete(self, key):
        key_hash = self._get_hash(key)

        if self.map[key_hash] is None :
            return False
        for i in range(0, len(self.map[key_hash])):
            if self.map[key_hash][i][0] == key:
                self.map[key_hash].pop(i)
                return True

    def print(self):

        print('---Phonebook---')
        for item in self.map:
            if item is not None:
                print(str(item))

h = HashMap()

7

在这种情况下,Python Counter也是一个不错的选择:

from collections import Counter

counter = Counter(["Sachin Tendulkar", "Sachin Tendulkar", "other things"])

print(counter)

这将返回一个字典,其中包含列表中每个元素的计数:

Counter({'Sachin Tendulkar': 2, 'other things': 1})

1

在python中,您将使用字典。

这是python中非常重要的类型,经常使用。

您可以轻松创建一个

name = {}

字典有很多方法:

# add entries:
>>> name['first'] = 'John'
>>> name['second'] = 'Doe'
>>> name
{'first': 'John', 'second': 'Doe'}

# you can store all objects and datatypes as value in a dictionary
# as key you can use all objects and datatypes that are hashable
>>> name['list'] = ['list', 'inside', 'dict']
>>> name[1] = 1
>>> name
{'first': 'John', 'second': 'Doe', 1: 1, 'list': ['list', 'inside', 'dict']}

您不能影响命令的顺序。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.