dictionaries - returning a key from a value

Avell Diroll avelldiroll at yahoo.fr
Fri Sep 1 08:40:03 EDT 2006


Michael Malinowski wrote:
(snip)
> However, I am curious to know if its possible to get the key from giving
> a value (basically the opposite of what I did above, instead of getting
> a value from a key, I want the key from a value). Is there a way of
> doing this? Or would I need to cycle all the keys until I hit a value
> match (which seems somewhat cumbersome).
(snip)

I believe you need to cycle through the entire dict (but that's what a
dict.<method> would do ... wouldn't it?) ... but it is really quickly
done using list comprehension (in Ipython shell here):

In [30]: sampledict={'the Holy Grail':'1975', 'Life of Brian':'1979',
'Party Political Broadcast':'1974','Mr. Neutron':'1974',
'Hamlet':'1974', 'Light Entertainment War':'1974'}

In [31]: sampledict Out[31]:
{'Hamlet': '1974',
 'Life of Brian': '1979',
 'Light Entertainment War': '1974',
 'Mr. Neutron': '1974',
 'Party Political Broadcast': '1974',
 'the Holy Grail': '1975'}

In [32]: sampledict.get('the Holy Grail') Out[32]: '1975'

In [33]: sampledict['Mr. Neutron'] Out[33]: '1974'

In [34]: keys = [key for key in sampledict if sampledict[key] == '1974']
In [35]: keys
Out[35]:
['Mr. Neutron',
 'Hamlet',
 'Party Political Broadcast',
 'Light Entertainment War']




HIH

Avell




More information about the Python-list mailing list