dictionaries - returning a key from a value

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Sep 1 09:54:04 EDT 2006


Avell Diroll:

keys = [key for key in sampledict if sampledict[key] == '1974']

Or better, given:

sampledict = {'the Holy Grail':1975, 'Life of Brian':1979,
              'Party Political Broadcast':1974,'Mr. Neutron':1974,
              'Hamlet':1974, 'Light Entertainment War':1974}

keys = [key for key,year in sampledict.iteritems() if year == 1974]
print keys

Another solution is a two-way (bidirectional) dict:
http://cheeseshop.python.org/pypi/two_way_dict/0.2

Bye,
bearophile




More information about the Python-list mailing list