简体   繁体   中英

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,

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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