How to add a new item to a python dictionary
In this article, you will learn about how to add a new item to a Python dictionary.
In the Python programming language, a dictionary is considered as a data structure that can hold multiple types of data as key: value. You may create a dictionary by typing curly braces and can store multiple types of data values in key: value pairs. It does not allow you to duplicate a value but you can add a new item to a python dictionary and in this article, we will explore how we can perform this action. Before doing so, let’s see an example of a python dictionary in the below section.
student = {
"name" : "Alex",
"age" : 24,
"roll" : 1704030
}
print (student)
# {'name': 'Alex', 'age': 24, 'roll': 1704030}
Here, you can see a simple example of a python dictionary named student. If you notice, you may be able to see that we are storing both string and integer in that dictionary and the values are stored in key: value pairs.
Now, what if you need to add a new item to this dictionary. For example, you need to add a subject as a new item. Python does not provide any built-in methods for adding a new item to a dictionary. But do not need to worry about this, you may add a new item to a python dictionary by using a new index key and assigning a value to it. See the below code example:
student = {
"name" : "Alex",
"age" : 24,
"roll" : 1704030
}
# Before adding a new Item
print (student)
student["Subject"] = "CSE"
# After Adding a new Item
print(student)
# Output:
# {'name': 'Alex', 'age': 24, 'roll': 1704030}
# {'name': 'Alex', 'age': 24, 'roll': 1704030, 'Subject': 'CSE'}
Here, you can see that we have added a new item successfully to a python list by using a new index key, and our new item subject and its value CSE is showing in the output.
There is another way of performing this action and that is using the update() method. Though the update()
method is basically used to update the value of an existing item, you can also add a new item by using it. Let’s see the below code example, where we will add gender as a new item and set its value as male in the Python dictionary.
student = {
"name" : "Alex",
"age" : 24,
"roll" : 1704030
}
# Before adding a new Item
print (student)
student.update({"gender" : "Male"})
# After Adding a new Item
print(student)
# Output:
# {'name': 'Alex', 'age': 24, 'roll': 1704030}
# {'name': 'Alex', 'age': 24, 'roll': 1704030, 'gender': 'Male'}
Here, you can see that we are getting our desired output and our new item has been added successfully with the help of the update()
method.
Adding a new item to a python dictionary is as simple as this and for adding a new item in a python dictionary you may follow these approaches.