[Tutor] Dictionary Values Questions

Kent Johnson kent37 at tds.net
Tue May 1 17:59:29 CEST 2007

Tony Waddell wrote:
> I am wondering how look for a key in a dictionary, given a value.
> I have a dictionary similar to this:
> a = { 'a1':1, 'a2':2, 'a3':3, 'a4'.:4}
> If I have the value of 2, how would I look at the dictionary to turn
> that into 'a2'.

You have to search the values. This will produce a list of all keys that 
have a given value (there could be zero, one or more):
[ key for key, value in a if value==2 ]

If you have to do this often you might consider keeping a reverse-lookup 
dictionary or perhaps your key-value relationship is backwards. You 
might be interested in these recipes:


More information about the Tutor mailing list