newbie: dictionary - howto get key value

Bengt Richter bokr at oz.net
Mon Mar 14 08:48:07 CET 2005


On Mon, 14 Mar 2005 05:02:25 GMT, Joal Heagney <joal at bigpond.net.au> wrote:

>Tim Roberts wrote:
>> "G. Völkl" <gm.voelkl at t-online.de> wrote:
>> 
>>>I use a dictionary:
>>>
>>>phone = {'mike':10,'sue':8,'john':3}
>>>
>>>phone['mike']   --> 10
>>>
>>>I want to know who has number 3?
>>>
>>>3 -->  'john'
>>>
>>>How to get it in the python way ?
>> 
>> 
>> If you need to do this a lot, just keep two dictionaries, where the keys in
>> each are the values in the other.
>> 
>>   reversephone = dict( zip( phone.values(), phone.keys() ) )
>
>(Been away from python for a while, so forgive me if I'm asking a silly 
>question.)
>Does python guarantee that the lists given by phone.values() and 
>phone.keys() are in mutual order? Or is it possible that python will 
>return the lists in different orders for .values() and .keys()?
>
Good question. I don't know. I hope so, but I would tend to write dict((v,k) for k,v in phone.items())
to do the equivalent, but note that it only works if everyone has a different phone number.

 >>> dict((v,k) for k,v in {'sue':3, 'bob':4}.items())
 {3: 'sue', 4: 'bob'}
 >>> dict((v,k) for k,v in {'sue':3, 'bob':4, 'mike':4}.items())
 {3: 'sue', 4: 'bob'}

Surprised at who got left out?
 >>> {'sue':3, 'bob':4, 'mike':4}.items()
 [('sue', 3), ('mike', 4), ('bob', 4)]

Regards,
Bengt Richter



More information about the Python-list mailing list