我想在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")

当前回答

Python字典是一种内置类型,支持键值对。它是相对于Java的HashMap最近的内置数据结构。

你可以声明一个键值对为值的dict:

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

你也可以在创建后设置一个键值映射:

streetno = {}
streetno["1"] = "Sachin Tendulkar"
print(streetno["1"]) # => "Sachin Tendulkar"

另一种创建字典的方法是使用内置函数dict(),但这仅在键是有效标识符时有效:

streetno = dict(one="Sachin Tendulkar", two="Dravid")
print(streetno["one"]) # => "Sachin Tendulkar"

其他回答

下面是使用python实现哈希映射 为了简单起见,哈希映射的大小是固定的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

这就是我对LeetCode问题706的解决方案:

一个哈希映射类,有三个方法:get、put和remove

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


class MyHashMap:

    def __init__(self, size=100):
        self.items = [None] * size
        self.size = size

    def _get_index(self, key):
        return hash(key) & self.size-1

    def put(self, key: int, value: int) -> None:
        index = self._get_index(key)
        item = self.items[index]
        if item is None:
            self.items[index] = Item(key, value)
        else:
            if item.key == key:
                item.value = value

            else:
                while True:
                    if item.key == key:
                        item.value = value
                        return
                    else:
                        if not item.next:
                            item.next = Item(key, value)
                            return
                        item = item.next



    def get(self, key: int) -> int:
        index = self._get_index(key)
            
        if self.items[index] is None:
            return -1
        item = self.items[index]
        while True:
            if item.key == key:
                return item.value
            else:
                if item.next:
                    item = item.next
                else:
                    return -1
        
        

    def remove(self, key: int) -> None:
        value = self.get(key)
        if value > -1:
            index = self._get_index(key)
            item = self.items[index]
            if item.key == key:
                self.items[index] = item.next if item.next else None
                return
                
            while True:
                if item.next and item.next.key == key:
                    item.next = item.next.next
                    return
                else:
                    if item.next:
                        item = item.next
                    else:
                        return

Python Counter在这种情况下也是一个很好的选择:

from collections import Counter

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

print(counter)

这将返回一个包含列表中每个元素计数的dict:

Counter({'Sachin Tendulkar': 2, 'other things': 1})
streetno = { 1 : "Sachin Tendulkar",
            2 : "Dravid",
            3 : "Sehwag",
            4 : "Laxman",
            5 : "Kohli" }

和检索值:

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

Or

name = streetno[3]

这是用数字作为键,在数字周围加上引号,用字符串作为键。

在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']}

你不能影响字典的顺序。