python reverse dictionary

16,085

If you want to invert the dictionary without changing its id you need to build a temporary dictionary, clear the old one, and update it. Here's how to do that using a dictionary comprehension.

d = {'name': 'Luke', 'age': 43, 'friend': 'Joe'}
print(d, id(d))

# Invert d
t = {v: k for k, v in d.items()}

# Copy t to d
d.clear()
d.update(t)
# Remove t
del t
print(d, id(d))

output

{'name': 'Luke', 'age': 43, 'friend': 'Joe'} 3072452564
{'Luke': 'name', 43: 'age', 'Joe': 'friend'} 3072452564

Tested using Python 3.6, which preserves the order of plain dictionaries. It's not strictly necessary to del t, but you might as well if you don't need it. Of course, if you're doing this inside a function t will get garbage collected as soon as it goes out of scope anyway.

You need to be careful when doing this: all the values must be immutable objects, and any duplicated values will get clobbered.

Also, while it's perfectly legal, some people consider it bad style to have mixed types for your dictionary keys. And if you want to create a sorted list of the dict's items you won't be able to do that easily in Python 3 if the keys are of mixed types. You can't sort keys of mixed types because Python 3 doesn't permit you to compare objects of mixed type.

Share:
16,085
Guy L
Author by

Guy L

Updated on August 20, 2022

Comments

  • Guy L
    Guy L almost 2 years

    given a dictionary:

     d = {'name': 'Luke', 'age': 43, 'friend': 'Joe'}
    

    i'm trying to build a function that will change it so that the new dictionary will be:

    d = {'Luke': 'name', 43: 'age', 'Joe':'friend'}
    

    in other words the key will become the values and the values will become the keys. also the id of the dictionary wont change.

    i tried this code:

    dict(map(reversed, d.items()))
    

    i'm using python 3.x any help will be appreciated.