我想在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中的字典是实现这一点的最佳方式。我们可以使用给定的<key,value>对创建以下字典:

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

要提取特定键的值,我们可以直接使用d[key]:

name = d["1"] # The value of name would be "Sachin Tendulkar" here

其他回答

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

from collections import Counter

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

print(counter)

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

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

它是Python内置的。看字典。

根据你的例子:

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

然后你可以像这样访问它:

sachine = streetno["1"]

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

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

和检索值:

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

Or

name = streetno[3]

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

Python中的字典是实现这一点的最佳方式。我们可以使用给定的<key,value>对创建以下字典:

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

要提取特定键的值,我们可以直接使用d[key]:

name = d["1"] # The value of name would be "Sachin Tendulkar" here

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

你不能影响字典的顺序。