Practical Solutions and Examples
Inverting a Dictionary with Unique Values
Here's an example of inverting a dictionary with unique values:
original_dict = {
"apple": 1,
"banana": 2,
"cherry": 3
}
inverted_dict = {value: key for key, value in original_dict.items()}
print(inverted_dict) ## Output: {1: 'apple', 2: 'banana', 3: 'cherry'}
In this example, we use a dictionary comprehension to create a new dictionary where the keys and values are swapped.
Inverting a Dictionary with Duplicate Values
When dealing with a dictionary that has duplicate values, we can use a defaultdict
from the collections
module to handle the inversion process:
from collections import defaultdict
original_dict = {
"apple": 1,
"banana": 2,
"cherry": 1,
"date": 2
}
inverted_dict = defaultdict(list)
for key, value in original_dict.items():
inverted_dict[value].append(key)
print(dict(inverted_dict)) ## Output: {1: ['apple', 'cherry'], 2: ['banana', 'date']}
In this example, we create a defaultdict
with the default value being an empty list. As we iterate through the original dictionary, we append the keys to the list associated with the corresponding value in the inverted dictionary.
Handling Duplicate Values with a Counter
Another approach to inverting a dictionary with duplicate values is to use the Counter
class from the collections
module. This allows us to count the occurrences of each value and then create the inverted dictionary accordingly.
from collections import Counter
original_dict = {
"apple": 1,
"banana": 2,
"cherry": 1,
"date": 2
}
counter = Counter(original_dict.values())
inverted_dict = {value: [key for key, v in original_dict.items() if v == value] for value in counter}
print(inverted_dict) ## Output: {1: ['apple', 'cherry'], 2: ['banana', 'date']}
In this example, we first create a Counter
object to count the occurrences of each value in the original dictionary. Then, we use a dictionary comprehension to create the inverted dictionary, where the keys are the unique values from the original dictionary, and the values are lists of the corresponding keys.
By understanding these practical solutions and examples, you'll be able to effectively invert dictionaries with both unique and duplicate values in your Python projects.