方法一:
mydict={'one':1, 'two':2, 'ntwo':2}
for key, val in mydict.items():
if val == 2:
print(key)
这种方法放第一位是因为,代码好读懂,而且适用于一值多键,
而下面的方法二要改进才能实现着效果就会麻烦许多,适用于一值一键。
如果出现这种情况:
dict={'one': [1, 11]}
那么得到字典的 值 是一个 列表(list),这时候要先判断 值 的类型是不是一个 list类型:
if isinstance(dict['one'], list): # if isinstance(dict[key], list) is true,
print('list: ', dict['one']) # using a for loop checks the each value of the list
# if find the value, print the key
方法二:
print(
list(mydict.keys())[list(mydict.values()).index(2)]
)
把字典中的键按循序存入列表:list(mydict.keys())
再把字典中的值全部存入另一个列表里:list(mydict.values())
两个列表的位置是相对应的:
['one', 'two', 'ntwo'] # list(mydict.keys())
[1, 2, 2] # list(mydict.values())
所以: list(mydict.values()).index(2) # index(2)得到的是 [1, 2, 2]的下标 1 而不是 2
# 这个1是 [1, 2, 2] 中第一个2的下标 # 就可以对应到 ['one', 'two', 'ntwo']
但是只能找到 two 不能找到 ntwo, 因为index(2)只返回第一个2的index。