[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:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415903
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252143
Kent
More information about the Tutor
mailing list