This tutorial will discuss multiple ways to add new key-value pair to dictionary in Python.
Table Of Contents
Method 1: Using dict.update() method
To add a new key-value pair to a dictionary, we can use the update method of a dictionary. It accepts an iterable sequence of key-value pairs as an argument and appends these key-value pairs into the dictionary.
To add a new key-value pair to a dictionary, we can enclose the key-value pair in curly braces and pass that to the update function. This will add the given key-value pair into the dictionary. Like this,
# Create a dictionary to store employee information employee_data = dict({"John Kumar": 35, "Ravi Smith": 28, "Emily Arora": 42}) # Add an employee information to the dictionary # as a new key-value pair employee_data.update({"Shobha Roy": 31})
It will add the new key-value pair into the dictionary.
If the given key already exists in the dictionary, then the update method will update the value of that existing key with the new value that we passed as the key-value pair argument to the update function.
Let’s see the complete example,
Frequently Asked:
# Create a dictionary to store employee information employee_data = dict({"John Kumar": 35, "Ravi Smith": 28, "Emily Arora": 42}) # Add an employee information to the dictionary # as a new key-value pair employee_data.update({"Shobha Roy": 31}) # Print the employee data print(employee_data)
Output
{'John Kumar': 35, 'Ravi Smith': 28, 'Emily Arora': 42, 'Shobha Roy': 31}
Method 2: Using [] Operator of Dictionary
We can also use square brackets ([]) to add a key-value pair into a dictionary.
For this, we will pass the key into the square brackets and assign a value to it, which will add the key-value pair into the dictionary. But if the given key already exists in the dictionary, it will update the value of that existing key.
Let’s see the complete example,
# Create a dictionary to store employee information employee_data = {"John Kumar": 35, "Ravi Smith": 28, "Emily Arora": 42} # Add an employee information to the dictionary # as a new key-value pair employee_data["Shobha Roy"] = 31 # Print the employee data print(employee_data)
Output
{'John Kumar': 35, 'Ravi Smith': 28, 'Emily Arora': 42, 'Shobha Roy': 31}
It added a new key-value pair into the Dictionary in Python.
Summary
Today, we learned about multiple ways to add new key-value pair to dictionary in Python.