0

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!

Hafiz Temuri
  • 3,882
  • 6
  • 41
  • 66
  • 1
    You're kind of defeating the whole point of using a Dictionary. Dictionaries and any sort of hash tables typically assumes you always know the keys to achieve a static constant performance for lookups. While you may be able to do a reverse lookup, the performance will most likely suffer. Hence, my earlier point about defeating the very purpose of using Dictionary in the first place. – Edward L. Mar 20 '15 at 04:46
  • I know, but I am kinda struck somewhere in my program and I have no other way but to go reserve, that's why I need to know. If that makes any sense! – Hafiz Temuri Mar 20 '15 at 04:56

2 Answers2

1

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.

Community
  • 1
  • 1
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • 3
    With this approach, you will never get `Doc1` by `4`. – Ozgur Vatansever Mar 20 '15 at 05:24
  • ozgur is correct. dictionaries do not allow duplicate keys. This would only work reliably if the values in your original dictionary are unique. – Edward L. Mar 20 '15 at 15:34
  • That changes nothing. Ordered dictionary are simply dictionaries that remembers the order in which keys are added to the collection for the purposes of enumeration. If duplicate keys exist, it will overwrite the previous entry with the new entry. Hence, it still will not work reliably. – Edward L. Mar 20 '15 at 19:38
0
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])
Nizam Mohamed
  • 8,751
  • 24
  • 32