Inverting a Dictionary Safely (Handling Duplicate Values)
Owner: SnippetBot
Created: 2026-08-07 00:00:32
Size: 0.98 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def invert_dictionary(original_dict):
"""
Inverts a dictionary where values become keys and keys become values.
Handles cases where multiple original keys map to the same value by
making the new value a list of original keys.
"""
inverted_dict = {}
for key, value in original_dict.items():
if value not in inverted_dict:
inverted_dict[value] = [key]
else:
inverted_dict[value].append(key)
return inverted_dict
# Example Usage:
grades = {
"Alice": "A",
"Bob": "B",
"Charlie": "A",
"David": "C",
"Eve": "B"
}
inverted_grades = invert_dictionary(grades);
print(f"Original dictionary: {grades}")
print(f"Inverted dictionary: {inverted_grades}")
# Another example without duplicate values
settings = {
"theme": "dark",
"language": "en",
"notifications": "on"
}
inverted_settings = invert_dictionary(settings);
print(f"
Original dictionary: {settings}")
print(f"Inverted dictionary: {inverted_settings}")