[Tutor] Question about Dictionaries

Emile van Sebille emile at fenx.com
Mon Aug 16 21:24:20 CEST 2010

On 8/16/2010 10:44 AM Chorn, Guillaume said...
> Hi All,
> I know that I can look up the value for a particular key in a
> dictionary, but can I look up the key associated with a particular
> value?

Yes.  But you'll need to implement it.  There are likely modules out 
there that'll do this, but it'd take more time to look up and evaluate 
than to simply write and implement exactly what you need.

> I understand that this could be problematic from the standpoint
> of multiple keys having the same value, but even then I feel like Python
> could just return a list of keys with that value.

So, in untested code you'd have a function something like:

result = []

for ky, val in dict.items():
   if val == targetval:
return result

If you need repeated access such that iterating over a large dict 
frequently impacts performance, you could subclass dict and maintain a 
second index allowing instant access to the keys associated with a 
specific value.



More information about the Tutor mailing list