954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Invert a Dictionary

Is there a good way to invert dictionary so key:value gets to be value:key?

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

Hi!

>>> d = {"a": "one", "b": "two", "c": "three"}
>>> inverted = dict([[v,k] for k,v in d.items()])
>>> inverted
{'three': 'c', 'two': 'b', 'one': 'a'}

And here is a clever way I found to invert a dict where some keys have the same value:

>>> def invert_dict(d):
...     inv = {}
...     for k,v in d.iteritems():
...         keys = inv.setdefault(v, [])
...         keys.append(k)
...     return inv
...
>>> d = {"a": "one", "b": "one", "c": "three"}
>>> invert_dict(d)
{'three': ['c'], 'one': ['a', 'b']}


Regards, mawe

mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

Thanks much mawe!

All these >>> and ....... mess me up, so I always take time to remove them so I can use my IDE editior to run the code.

It looks like its workoing so.

How would invert a dictionary like:

{'A':['Art', 'Army','Apple'], 'B':['Ball','Boy','Bang','Brother']}

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

Hi!

All these >>> and ....... mess me up, so I always take time to remove them so I can use my IDE editior to run the code.


Sorry. I play with Python in its interactive mode and there you have all these >>> and ... ;) I will post the codes without them (just for you :))How would invert a dictionary like:
{'A':['Art', 'Army','Apple'], 'B':['Ball','Boy','Bang','Brother']}

def invert(d):
    return dict((v,k) for k in d for v in d[k])

d = {'A':['Art', 'Army', 'Apple'], 'B':['Ball', 'Boy', 'Bang', 'Brother']}
print invert(d)
# {'Boy': 'B', 'Ball': 'B', 'Art': 'A', 'Apple': 'A', 'Army': 'A', 'Brother': 'B', 'Bang': 'B'}


Regards, mawe

mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

Thank you much again mawe,

I slowly getting to know what dictionaries are about. Looks like they are very usefull. Sorry I am asking so many naive questions.

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You