Append a Key to a Python Dictionary
Last Updated :
15 Feb, 2024
We can append or add and update the value of key in dictionary using various methods. In this article, we will explore three different methods to achieve this task: Using update() method, Using merge operator (“|”), Using update operator(“|=”), Adding key with value, Adding key without value.
Example :
Input: Dictionary ={ 'gfg': 3, 'geeks': 5, 'for': 2, 'geek': 4, 'tutorial': 8}
Key = Python, value = 6
Output: { 'gfg': 3, 'geeks': 5, 'for': 2, 'geek': 4, 'tutorial': 8, 'Python':6}
How to Append a Key to a Dictionary Python?
Below are the methods of How to Append a Key to a Dictionary in Python.
Append a Key to a Dictionary by Adding Key with Value
In this example, below code initializes a dictionary with predefined key-value pairs and then adds a new key “Python” with the value 6 to the dictionary before printing the updated dictionary.
Python3
Dictionary = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
key = "Python"
value = 6
Dictionary[key] = value
print (Dictionary)
|
Output
{'gfg': 3, 'geeks': 5, 'for': 2, 'geek': 4, 'tutorial': 8, 'Python': 6}
Append a Key to a Dictionary Python Using Update() Method
In this example, The code merges `Dictionary_2` into `Dictionary_1` using the `update()` method, adding the key “Python” with the value 6 to the original dictionary, and prints the updated result.
Python3
Dictionary_1 = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
Dictionary_2 = { 'Python' : 6 }
Dictionary_1.update(Dictionary_2)
print (Dictionary_1)
|
Output
{'gfg': 3, 'geeks': 5, 'for': 2, 'geek': 4, 'tutorial': 8, 'Python': 6}
Append a Key to a Dictionary Python Using setdefault()
Method
In this example, below code initializes a dictionary, `my_dict`, and uses the `setdefault()` method to add a new key-value pair (‘Python’, 6). If ‘Python’ is not already a key, it is added with the value 6. The updated dictionary is printed.
Python3
my_dict = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
my_dict.setdefault( 'Python' , 6 )
print (my_dict)
|
Output
{'gfg': 3, 'geeks': 5, 'for': 2, 'geek': 4, 'tutorial': 8, 'Python': 6}
Append a Key to a Dictionary Python Using dict
Constructor
In this example, below code initializes a dictionary, `my_dict`, and uses the `dict` constructor to add a new key-value pair (‘Python’, 6). The existing key-value pairs from `my_dict` are combined with the new pair, creating an updated dictionary. The result is then printed.
Python3
my_dict = { 'gfg' : 3 , 'geeks' : 5 , 'for' : 2 , 'geek' : 4 , 'tutorial' : 8 }
my_dict = dict (my_dict, Python = 6 )
print (my_dict)
|
Output
{'gfg': 3, 'geeks': 5, 'for': 2, 'geek': 4, 'tutorial': 8, 'Python': 6}
Share your thoughts in the comments
Please Login to comment...