Reverting (key, value) pairs in a dictionary
Stephen Horne
steve at ninereeds.fsnet.co.uk
Thu Oct 30 21:10:26 EST 2003
On Thu, 30 Oct 2003 16:27:13 -0500, Shu-Hsien Sheu <sheu at bu.edu>
wrote:
>Hi,
>
>How do you turn a dictionary of <original_key>: <original_value> into
><original_value>: <original_key>, when there is no duplicate values?
>For instance, I have a dictionary kk:
>kk = {'abc': ['B', 'C', 'D', 'E'], 'def':['G', 'H']}
>
>and I want a new dictionary newkk which looks like:
>newkk = {'B':'abc', 'C':'abc', 'D':'abc', 'E':'abc', 'G':'def', 'H':'def'}
There will be loads of ways of doing this. I would probably use a list
comprehension such as...
result = dict( [(d, k) for k, l in <dict>.items () for d in l] )
Generator comprehensions may make this a tad neater in Python 2.4 ;-)
List comprehensions aren't to everyones taste, though, so some people
would probably find the following clearer...
result = {}
for k, l in <dict>.items () :
for d in l :
result [d] = k
The only flaw in your own code is that creating the list of lists in
'new' is redundant - it is more efficient to create the dictionary
directly.
--
Steve Horne
steve at ninereeds dot fsnet dot co dot uk
More information about the Python-list
mailing list