[dictionary] how to get key by item

Nick Coghlan ncoghlan at iinet.net.au
Tue Dec 14 12:55:59 CET 2004


Ola Natvig wrote:
> If some keys has the same value as the item this will cause problems 
> because keys in your result dictionary can be overwritten. Could it be a 
>  option to build the result dictionary as a dictionary with the values 
> as the keys, and lists of keys as the value. Perhaps you need to use a 
> loop for this.
> 

<<Python 2.4>>

.>>> d = dict(foo=1, bar=1, bob=7, jane=42, mary=16, fred=16)
.>>> from itertools import groupby
.>>> val = d.__getitem__
.>>> grouped = groupby(sorted(d.iterkeys(), key=val), val)
.>>> r = dict((value, list(keys)) for value, keys in grouped)
.>>> r
{16: ['mary', 'fred'], 1: ['bar', 'foo'], 42: ['jane'], 7: ['bob']}

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list