newbie: dictionary - howto get key value

bruno modulix onurb at xiludom.gro
Thu Mar 10 12:56:41 EST 2005


G. Völkl wrote:
> Hello,
> 
> I use a dictionary:
> 
> phone = {'mike':10,'sue':8,'john':3}
> 
> phone['mike']   --> 10
> 
> I want to know who has number 3?
> 3 -->  'john'

Note that you can have many keys with the same value:
phone = {'mike':10,'sue':8,'john':3, 'jack': 3, 'helen' : 10}


> How to get it in the python way ?

simplest way I could think of in 30':
def key_from_value(aDict, target):
   return [key for key, value in aDict.items() if value==target]

key_from_value(phone, 3)
--> ['john', 'jack']

but this is a linear search, so not very efficient if phone is big.
Then you may want to maintain a reversed index:
(here again, simplest way I could think of)

def rev_index(aDict):
   r = {}
   for key, value in aDict.items():
     if r.has_key(value):
       r[value].append(key)
     else:
       r[value] = [key]
    return r
rev_phone = rev_index(phone)
rev_phone
--> {8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']}

{8: ['sue'], 10: ['helen', 'mike'], 3: ['john', 'jack']}

rev_phone[3]
--> ['john', 'jack']

But now you've got another problem : you need to update the reversed 
index each time you modify the dictionary... Which would lead to writing 
a class extending dict, maintaining a reversed index, and exposing extra 
methods to handle this.

But there may be a better way (someone else ?)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list