How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python.
Adding the Same Key Value in Python
Dictionaries in Python are unordered collections of key-value pairs where each key must be unique. If we repeat the key then the latest value assigned to that key will overwrite the previous one. This behavior ensures that each key maps to exactly one value.
To handle the need for adding the same key values, you can use different methods to store multiple values under a single key. These methods include using lists as values and defaultdict
from the collections
module. Let us see these ] methods in detail.
Using List as Values
In this example, we will use a Python list of values as the value of the keys of the Dictionaries. We will convert the value of the same key in a single list and then use that list as the value of that key.
# function to add key vales
def add_pair(dictionary, key, value):
if key in dictionary:
dictionary[key].append(value)
else:
dictionary[key] = [value]
# initialize dictionary
my_dict = {}
# key value pair 1
add_pair(my_dict, 'a', 1)
add_pair(my_dict, 'a', 1)
# key value pair 2
add_pair(my_dict, 'b', 2)
add_pair(my_dict, 'b', 2)
print(my_dict)
Output
{'a': [1, 1], 'b': [2, 2]}
Using defaultdict
In this example, we use the defaultdict function of the
collections module
, which
allows for automatic handling of keys that do not yet exist.
# import collection module
from collections import defaultdict
# function to add key vales
def add_pairs(dictionary, key, value):
dictionary[key].append(value)
# initialize dictionary
my_dict = defaultdict(list)
# key value pair 1
add_pairs(my_dict, 'a', 1)
add_pairs(my_dict, 'a', 1)
# key value pair 2
add_pairs(my_dict, 'b', 2)
add_pairs(my_dict, 'b', 2)
print(my_dict)
Output
defaultdict(<class 'list'>, {'a': [1, 1], 'b': [2, 2]})
Conclusion
While Python dictionaries do not allow duplicate keys, you can still manage and store multiple values for the same key using lists, nested dictionaries, defaultdict
, or a dictionary of lists. These methods provide flexible and efficient ways to handle such requirements.