我做了一个函数,它将在字典中查找年龄并显示匹配的名字:
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
if age == search_age:
name = dictionary[age]
print name
我知道如何比较和查找年龄,只是不知道如何显示这个人的名字。此外,由于第5行,我得到了一个KeyError。我知道这是不正确的,但我不知道如何让它向后搜索。
这是一个奇怪的问题,因为第一条评论就给出了完美的答案。
根据样例提供的数据示例
dictionary = {'george': 16, 'amber': 19}
print(dictionary["george"])
它返回
16
所以你想要相反的结果
输入“16”,得到“george”
简单地交换键值和presto
dictionary = {'george': 16, 'amber': 19}
inv_dict = {value:key for key, value in dictionary.items()}
print(inv_dict[16])
我处于完全相反的位置,因为我有一本字典
{16:'george', 19:'amber'}
我试着喂"乔治"然后得到16个…我尝试了几种循环和迭代器,OK..他们工作,但它不是简单的一行解决方案,我将使用快速结果…所以我简单地交换了解。
如果我错过了什么,请让我知道删除我的答案。
mydict = {'george': 16, 'amber': 19}
print mydict.keys()[mydict.values().index(16)] # Prints george
或者在Python 3.x中:
mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george
基本上,它将字典的值分离到一个列表中,找到所拥有值的位置,并在该位置获取键。
更多关于Python 3中的keys()和.values():如何从dict获取值列表?
以下是我的看法。这对于显示多个结果很有好处,以防您需要一个结果。所以我也添加了这个列表
myList = {'george':16,'amber':19, 'rachel':19,
'david':15 } #Setting the dictionary
result=[] #Making ready of the result list
search_age = int(input('Enter age '))
for keywords in myList.keys():
if myList[keywords] ==search_age:
result.append(keywords) #This part, we are making list of results
for res in result: #We are now printing the results
print(res)
就是这样……