简体   繁体   English

如何在字典(Python 3.2)中通过“值”获取“键”

[英]How to get 'Keys' by 'Values' in Dictionary (Python 3.2)

I have seen so many similar problems but none of them is working for me. 我已经看到了很多类似的问题,但是没有一个对我有用。 I wonder if someone here can help me out. 我不知道这里有人可以帮助我。 I have a dictionary and I want to get its Key by its Value, as follows 我有一本字典,我想按其值获取其键,如下所示

dic = {'Doc4': 2, 'Doc3': 4, 'Doc1': 4, 'Doc2': 6}

That's what I have tried to get 'Doc4' but couldn't find a luck yet, 那就是我试图获得的“ Doc4”,但还没有找到好运,

dic.get(2) & dic.item(2) & dic.iteritem(2) & dic.value(2) & dic.key(2)

Thanks in Advance! 提前致谢!

You can access it this way: 您可以通过以下方式访问它:

def getval(dic, val):
    inv_dic = {v: k for k, v in dic.items()}
    return inv_dic[val]

As such: 因此:

>>> dic = {'Doc4': 2, 'Doc3': 4, 'Doc1': 4, 'Doc2': 6}
>>> getval(dic, 2)
'Doc4'
>>> 

First we invert the dictionary then we access the dictionary based on the value. 首先我们反转字典,然后根据该值访问字典。

from collections import defaultdict

dic = {'Doc4': 2, 'Doc3': 4, 'Doc1': 4, 'Doc2': 6}
rdic = defaultdict(list)
for k, v in dic.items():
    rdic[v].append(k)
for v in dic.values():
    print(v,rdic[v])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM