Sometimes you need to invert the keys and values in a dictionary. Fortunately, Python gives us a concise way to do exactly that with list comprehensions and dict.items():
person = {
"first_name": "Justin",
"job": "engineer",
"age": 100,
}
# Normally the word 'key' should be avoided, other languages like JS
# have that word reserved. In practice I'd use 'k' and 'v' here
inverted = {value: key for key, value in person.items()}
print(inverted)
"""
{
'Justin': 'first_name',
'engineer': 'job',
100: 'age'
}
"""
However, if you have nested dictionaries this method won’t work:
person = {
"first_name": "Justin",
"address": {
"street_1": "123 Main st",
"city": "New York City",
},
}
inverted = {v: k for k,v in person.items()}
// TypeError: unhashable type: 'dict'
This error is caused by attempting to use the entire "address"
dict as a key in the new inverted
dict. If you need to invert a dictionary which itself contains dictionaries or other unhashable types like lists
, the code gets complicated quickly and will vary based on exactly what you’re trying to accomplish.
Helpful Links
- The items() method – Python docs
- Python list comprehensions – Me!