Python笔记: 通过字典的值得到键

来源:互联网 发布:linux 翻到最后一页 编辑:程序博客网 时间:2024/06/05 19:28


方法一:

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)  # 得到的是 1 而不是 2

但是只能找到 two 不能找到 ntwo, 因为index(2)只返回第一个2的index。





原创粉丝点击