Horje
How to Add Duplicate Keys in Dictionary Python

In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will see how to store multiple values for a single key using two simple approaches.

Understanding Dictionary Key Constraints

In Python, dictionary keys must be unique. This means that if you try to add a key that already exists in the dictionary, the new value will overwrite the existing value. This behavior ensures that each key maps to one and only one value.

For Example:

Python
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict)

# The value 25 will be overwritten by 30
my_dict['age'] = 30
print(my_dict)

Output:

{'name': 'Alice', 'age': 25}
{'name': 'Alice', 'age': 30}

Workarounds for Duplicate Keys

Since dictionaries do not allow duplicate keys, you need to use alternative methods to achieve similar functionality. Here are a few common workarounds:

Use a List for Values

In this approach each key in the dictionary maps to a list of values. When we want to add a duplicate key, we append the new value to the existing list.

Python
# Initialize the dictionary
duplicate_dict = {}

# Function to add a key-value pair
def add_to_dict(key, value):
    if key in duplicate_dict:
        duplicate_dict[key].append(value)
    else:
        duplicate_dict[key] = [value]

# Add values to the dictionary
add_to_dict('Platform', 'GeeksForGeeks')
add_to_dict('Courses', 'MERN')
add_to_dict('Courses', 'DSA')

print(duplicate_dict)

Output:

{'Platform': ['GeeksForGeeks'], 'Courses': ['MERN', 'DSA']}

Use a Dictionary of Lists

In this approach each key in the main dictionary maps to another dictionary. The inner dictionary uses values as keys and the count of occurrences as values.

Python
# Initialize the dictionary
multi_value_dict = {}

# Function to add a key-value pair
def add_to_dict(key, value):
    if key not in multi_value_dict:
        multi_value_dict[key] = {}
    if value in multi_value_dict[key]:
        multi_value_dict[key][value] += 1
    else:
        multi_value_dict[key][value] = 1

# Add values to the dictionary
add_to_dict('Platform', 'GeeksForGeeks')
add_to_dict('Courses', 'MERN')
add_to_dict('Courses', 'DSA')
add_to_dict('Courses', 'DSA')


# Print the dictionary
print(multi_value_dict)

Output:

{'Platform': {'GeeksForGeeks': 1}, 'Courses': {'MERN': 1, 'DSA': 2}}

Conclusion

While Python dictionaries do not support duplicate keys directly, there are several effective workarounds to store multiple values under a single key. By using lists, nested dictionaries, or defaultdict, you can achieve the desired functionality and efficiently manage your data.

FAQs

Q: Can I use sets instead of lists for storing values?

Yes, use sets if you don’t care about the order and don’t want duplicate values.

Q: How can I get all values for a key?

In Approach 1, access the list for the key. In Approach 2, iterate over the inner dictionary to get values and their counts.

Q: What if I need to remove a specific value for a key?

In Approach 1, remove the value from the list. In Approach 2, decrease the count or remove the entry from the inner dictionary.




Reffered: https://www.geeksforgeeks.org


Python

Related
How Many Rows Can Pandas Dataframe Handle? How Many Rows Can Pandas Dataframe Handle?
How to Query as GROUP BY in Django? How to Query as GROUP BY in Django?
How to get GET request values in Django? How to get GET request values in Django?
How to Define Two Fields "Unique" as Couple in Django How to Define Two Fields "Unique" as Couple in Django
How to Compare List of Dictionaries in Python How to Compare List of Dictionaries in Python

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18