Reverting (key, value) pairs in a dictionary
Shu-Hsien Sheu
sheu at bu.edu
Thu Oct 30 16:27:13 EST 2003
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'}
My codes are:
>>> kk = {'abc': ['B', 'C', 'D', 'E'], 'def':['G', 'H']}
>>> new = []
>>> for i, item in kk.items():
for j in item:
new.append([j, i])
>>> newkk = dict(new)
>>> new
[['B', 'abc'], ['C', 'abc'], ['D', 'abc'], ['E', 'abc'], ['G', 'def'],
['H', 'def']]
>>> newkk
{'C': 'abc', 'B': 'abc', 'E': 'abc', 'D': 'abc', 'G': 'def', 'H': 'def'}
Is there a better way of doing it?
-shuhsien
More information about the Python-list
mailing list