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.