newbie: dictionary - howto get key value
bruno modulix
onurb at xiludom.gro
Thu Mar 10 13:07:39 EST 2005
Michael.Coll-Barth at VerizonWireless.com wrote:
(top-post corrected)
>>
>> -----Original Message-----
>> From:
>> python-list-bounces+michael.coll-barth=verizonwireless.com at python.org
>> [mailto:python-list-bounces+michael.coll-barth=verizonwireless.com at pytho
>> n.org]On Behalf Of G. Völkl
>> Sent: Thursday, March 10, 2005 12:19 PM
>> To: python-list at python.org
>> Subject: newbie: dictionary - howto get key value
>>
>>
>> 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 ?
> how about?
>
> test = 3 #find person with this number
> for x in xrange(len(phone.keys())):
> print x
> if phone[phone.keys()[x]] == test:
> print phone.keys()[x]
> break
>
> Being a newbie myself, I'd love a little critique on the above.
0/ does not retrieve all the information (just the first match)
1/ not reusable (hint : make it a function)
2/ does not retrieve the information, just print it
3/ also print some useless informations ('print x')
4/ makes len(phone.keys()) + 1 calls to phone.keys()
hint :
for key in phone.keys():
if phone[key] == test:
print phone[key]
or better:
for key, value in phone.items():
if value == test:
print key
> Be kind as
> I don't know what else needs to be done in Gerhard's process.
Hope I haven't been to harsh !-)
> Of course, we
> could put this loop in a call and return the name
yeps.
--
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