PYTHON

Invert a Dictionary (Values to Keys, Keys to Values)

Transform a Python dictionary by making its values new keys, and its original keys grouped into lists as the new values. Useful for creating reverse lookup maps and efficient data querying.

from collections import defaultdict

original_dict = {
    'apple': 'fruit',
    'banana': 'fruit',
    'carrot': 'vegetable',
    'broccoli': 'vegetable',
    'orange': 'fruit'
}

inverted_dict = defaultdict(list)
for key, value in original_dict.items():
    inverted_dict[value].append(key)

# Result (defaultdict converts to dict on print):
# {
#  'fruit': ['apple', 'banana', 'orange'],
#  'vegetable': ['carrot', 'broccoli']
# }
How it works: This snippet shows how to invert a dictionary, transforming its values into new keys and its original keys into values (specifically, lists of values). It uses `collections.defaultdict(list)` to automatically create a list for each new value-turned-key, allowing multiple original keys that mapped to the same value to be grouped together. This is highly useful for creating efficient reverse lookup structures.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs