newbie: dictionary - howto get key value

Jeremy Jones zanesdad at bellsouth.net
Thu Mar 10 12:28:01 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'
>
>How to get it in the python way ?
>
>Thanks
>       Gerhard
>
>
>  
>
How 'bout a list comprehension:

In [1]:phone = {'mike':10,'sue':8,'john':3, 'billy':3}

In [2]:phone.items()
Out[2]:[('billy', 3), ('mike', 10), ('john', 3), ('sue', 8)]

In [3]:[i[0] for i in phone.items() if i[1] == 3]
Out[3]:['billy', 'john']

I added an additional person named "billy" with a number of 3 since 
values in a dictionary don't have to be unique.


Jeremy Jones


More information about the Python-list mailing list