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

Recommended Answers

All 4 Replies

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

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':, 'B':}

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':, 'B':}

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.