How to get a key from dictionary?
Michael Chermside
mcherm at destiny.com
Mon Mar 25 17:30:54 EST 2002
> Hi,
> Is there a possibility to get, from a dictionary, a key according to a
> value ?
> For example
> I have a dictionary
>
> dict={'aa':1,'bb':2}
>
> and
> dict['aa']
> is 1
>
> But how can I for value 1 find out key? (That is here 'aa')
>
> Thank you for help
> Ladislav
Yes, you can get this information, but there are two things you should
be careful of:
1) The dictionary is designed so it is very fast to find the value
for a given key. Finding the key for a given value will be much
slower ( O(size-of-dictionary) to be specific ).
2) Sometimes a dictionary will have MORE THAN ONE key with the SAME
value. So maybe you want just any random key with that value, or
perhaps you want ALL the keys with that value. I'll show how to do
both.
Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> dict = {'aa': 1, 'bb':2, 'cc': 3, 'BB': 2}
>>> def getSomeKeyForValue( dict, valueToFind ):
"""Returns some random key with the given value, or
throws KeyException"""
for key, value in dict.iteritems():
if value == valueToFind:
return key
raise KeyException()
>>> getSomeKeyForValue( dict, 1)
'aa'
>>> getSomeKeyForValue( dict, 2)
'BB'
>>> getSomeKeyForValue( dict, 4)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in ?
getSomeKeyForValue( dict, 4)
File "<pyshell#7>", line 7, in getSomeKeyForValue
raise KeyException()
NameError: global name 'KeyException' is not defined
>>> def getAllKeysForValue( dict, valueToFind ):
"""Returns a list of the keys in dict with the given
value. If no value is found the list is of length 0."""
answer = []
for key, value in dict.iteritems():
if value == valueToFind:
answer.append(key)
return answer
>>> getAllKeysForValue( dict, 1 )
['aa']
>>> getAllKeysForValue( dict, 2 )
['BB', 'bb']
>>> getAllKeysForValue( dict, 4 )
[]
-- Michael Chermside
More information about the Python-list
mailing list