0

Possible Duplicate:
Most efficient method to get key for a value in a dict
Python: Modify a dict to make the key a value, and a value the key

In python, suppose we have a dictionary:

mydict = {'myKey': 'myValue'}

To get the value for myKey we do

myDict['myKey']

Suppose we need to do things the other way around. What is the easiest way to get the key for value my value?

Note: In this case my dictionary is static. The entries never change.

Community
  • 1
  • 1
dublintech
  • 16,815
  • 29
  • 84
  • 115
  • 1
    Is your mapping between keys and values bijective (one-to-one)? Or can a value potentially map back to multiple keys? – Alex Reynolds Feb 07 '12 at 21:20
  • I think I see what @AlexReynolds is getting at couldn't you simply create the reverse mapping in another dictionary. Any other solution of iterating across the dictionary and looking for your value may result in multiple keys if the answer to his question is no. In that case you could still build a second dictionary but storing the n-tuple set as the value. – shaunhusain Feb 07 '12 at 21:23

4 Answers4

1

This should work:

 keyPoint = [key for key, value in mydict.iteritems() if value == "myValue"][0]

this will return the value of the key.

Bry6n
  • 1,879
  • 1
  • 12
  • 20
0

you could make a reversed dict

revDict = dict((v,k) for k,v in myDict.items())

or this if all values are not distinct

revDict = defaultdict(list)
for k,v in myDict:
    revDict[v].append(k)
ptitpoulpe
  • 684
  • 4
  • 17
0

You can invert your dictionary into a value-to-list-of-keys arrangement using something like this:

newdict = {}
for k,v in mydict.iteritems():
    lst = newdict.get(v, [])
    newdict[v].append(k)

Then you could index into that reversed dictionary to find your key:

mykey = newdict.get(myvalue)
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
0

You could create a 'reversed' dictionary, since the initial dictionary is static:

>>> revdict = dict([(mydict[key],key) for key in mydict])
>>> revdict['myValue']
'myKey'
uselpa
  • 18,732
  • 2
  • 34
  • 52