Add Same Key in Python Dictionary
Last Updated :
20 Feb, 2024
In Python, dictionaries are a versatile data structure that allows you to store key-value pairs. If we want to add the same key with a new value to a dictionary, there are multiple methods to achieve this. In this discussion, we will explore different methods for adding the same key with a new value to a dictionary.
Add Same Key in the Dictionary in Python
Below are some of the ways by which we can add the same key in the dictionary in Python:
- Using Square Bracket Assignment
- Using the
update()
Method
- Using the
dict()
Constructor
- Using the
collections.defaultdict
Class
Add Same Key in Dictionary Using Square Bracket Assignment
In this method, we directly use square bracket assignment to update the value associated with the existing key in the dictionary.
Python3
my_dict = { 'a' : 1 , 'b' : 2 }
my_dict[ 'a' ] = 3
print ( "Square Bracket Assignment:" , my_dict)
|
Output
Square Bracket Assignment: {'a': 3, 'b': 2}
Add Same Key in Dictionary Using update()
Method
In this approach, update()
method is used to modify the dictionary. Here we can add a new key-value pair or update an existing key with a new value.
Python3
my_dict = { 'a' : 1 , 'b' : 2 }
my_dict.update({ 'a' : 3 })
print ( "update() Method:" , my_dict)
|
Output
update() Method: {'a': 3, 'b': 2}
Add Same Key in Dictionary Using the dict()
Constructor
In this approach, we use the dict()
constructor to create a new dictionary by merging the existing dictionary with a new key-value pair or updating an existing key with a new value.
Python3
my_dict = { 'a' : 1 , 'b' : 2 }
my_dict = dict (my_dict, a = 3 )
print ( "dict() Constructor:" , my_dict)
|
Output
dict() Constructor: {'a': 3, 'b': 2}
Add Same Key in Dictionary Using the collections.defaultdict
Class
In this method, we use the defaultdict
class from the collections
module. It allows setting a default value for any new keys, and we can update the value for an existing key.
Python3
from collections import defaultdict
my_dict = defaultdict( int , { 'a' : 1 , 'b' : 2 })
my_dict[ 'a' ] = 3
print ( "defaultdict Class:" , dict (my_dict))
|
Output
defaultdict Class: {'a': 3, 'b': 2}
Conclusion
We have covered easy methods on “How to Add Same Key in Dictionary Python”, we can easily add the same key value in dictionary using these methods. Adding values in a dictionary is very important for data manipulation, updation, deletion, etc.
Share your thoughts in the comments
Please Login to comment...