python - How to swap keys with values in a dictionary -
the output should contain keys , values original dictionary:
dicts = {1: 'a', 2: 'b', 3: 'a', 4: 'a'}
however, when try swap result is:
{'a': 4, 'b': 2}
how can solve problem?
not sure answering question fully, because bit confusing. in comments above, show want reverse key/value of 1 : a
'a' : 1
.
you might find collections module useful.
import collections d = collections.defaultdict(list) dicts = {1:'a', 2:'b', 3:'a', 4:'a'} key, value in dicts.items(): d[value].append(key)
then try output:
>>> d defaultdict(<type 'list'>, {'a': [1, 3, 4], 'b': [2]})
Comments
Post a Comment