Python 如何根据输入变量引用某个字典值
在python中,我要求用户输入目的地 我的字典如下。该值表示英里数Python 如何根据输入变量引用某个字典值,python,dictionary,Python,Dictionary,在python中,我要求用户输入目的地 我的字典如下。该值表示英里数 LocationsDict = {'Chicago': 220, 'Atlanta': 461} destination = str(input("What is your destination?")) 假设我在亚特兰大打字,理论上我应该能够输出英里数的值。 我已尝试执行以下操作以打印出英里数 print(LocationsDict.values()[destination]) 当我尝试这个时,我得到一个错误。我错过
LocationsDict = {'Chicago': 220, 'Atlanta': 461}
destination = str(input("What is your destination?"))
假设我在亚特兰大打字,理论上我应该能够输出英里数的值。
我已尝试执行以下操作以打印出英里数
print(LocationsDict.values()[destination])
当我尝试这个时,我得到一个错误。我错过了什么?如何引用基于变量的词典?我知道我可以做大量的if语句,但那太复杂了 dict.values()
返回该字典中值的列表视图
您应该使用括号符号dict[]
访问字典:
输出:
461
要修复错误,请执行以下操作:
LocationsDict = {'Chicago': 220, 'Atlanta': 461}
destination = str(input("What is your destination?"))
print(LocationsDict[destination])
但对于将来的错误处理,您可以尝试:
LocationsDict = {'Chicago': 220, 'Atlanta': 461}
destination = str(input("What is your destination?"))
try:
dist = LocationsDict[destination]
except:
dist = "There is no data on this location"
print(dist)
值
返回不支持索引的iterable;您可以将其用作for
循环,但不能直接使用。这就是你出错的地方:你试图把它当作原始的dict索引
>>> type(LocationsDict.values())
<class 'dict_values'>
>>> dist = LocationsDict.values()
>>> dist[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_values' object does not support indexing
如其他人所示,一种方法是正确调用底层访问例程:
>>> LocationsDict.get("Atlanta")
461
但是,最简单的方法是使用教程材料中的索引:
>>> LocationsDict["Atlanta"]
LocationsDict[destination]
是提取键对应的值或使用LocationsDict.get(destination)
@BtcSourcesdict.values()
不返回列表
…打印(键入(my_dict.values())
它给出了dict\u值
type@BtcSources这是给文档的一个例子。@Ch3steR你完全正确,我不是指确切的类型,而是给他一个想法,这就是为什么我没有把它作为代码。但它确实可能会误导,最好删除它。@BtcSources是的,它可能会让初学者感到困惑。这就是我不发布b的原因挑剔。;)不要使用try except
你可以使用dict.get(key,'not data on this loc')
你可以@Ch3steR,但我更喜欢这种方法(可能是因为我不知道你可以这样做!!!)
>>> list(dist)
[220, 461]
>>> dist["Atlanta"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_values' object is not subscriptable
>>> LocationsDict.values("Atlanta")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: values() takes no arguments (1 given)
>>> LocationsDict.get("Atlanta")
461
>>> LocationsDict["Atlanta"]