Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

python - Invert keys and values of the original dictionary

For example, I call this function by passing a dictionary as parameter:

>>> inv_map({'a':1, 'b':2, 'c':3, 'd':2})
{1: ['a'], 2: ['b', 'd'], 3: ['c']}
>>> inv_map({'a':3, 'b':3, 'c':3})
{3: ['a', 'c', 'b']}
>>> inv_map({'a':2, 'b':1, 'c':2, 'd':1})
{1: ['b', 'd'], 2: ['a', 'c']}

If

map = { 'a': 1, 'b':2 }

I can only invert this map to get:

inv_map = { 1: 'a', 2: 'b' }

by using this

dict((v,k) for k, v in map.iteritems())

Anyone knows how to do that for my case?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a defaultdict with list:

>>> from collections import defaultdict
>>> m = {'a': 2, 'b': 1, 'c': 2, 'd': 1}
>>> dd = defaultdict(list)
>>> for k, v in m.iteritems():
...     dd[v].append(k)
... 
>>> dict(dd)
{1: ['b', 'd'], 2: ['a', 'c']}

If you don't care if you have an dict or defaultdict, you can omit the last step und use the defaultdict directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...