Now that we have seen the basics of creating a dictionary. Let’s see how you can perform Python add to dictionary or add elements in the existing directory.
However, let’s first take a look at how to update the elements of the existing dictionary.
Table of Contents
Updating Existing element in Dictionary
For updating the existing element of the dictionary, you just need the key of the particular element of the dictionary.
For example – If you want to update the ‘Name’ element from ‘Alex’ to ‘John’. Then the syntax to do so is as follow:
Python Add to Dictionary by using subscript notation
Now that you know the process of updating the existing element. Let’s move on to our main topic which is how you can add new elements in our existing directory.
So, let’s take an example that we have already created a directory names ‘student’, which have 3 elements and we have to add more element in it.
student = {'Name': 'Alex', 'RollNo': 18, 'Section': 'B'}
print(student) #before adding the elements
student['Marks'] = 430
student['Course'] = 'Engineering'
print(student) #after adding the elements
Now that we have seen the Subscript Notation Method for adding the new elements in the dictionary.
Let’s take a look at another method for adding a new element in dictionary which is update() Method.
Update Method is more suitable, In case you want to add lot of new elements in your dictionary.
student = {'Name': 'Alex', 'RollNo': 18, 'Section': 'B'}
print(student) #before using update() method
student.update({'course':'Engineering'}) #adding single element
print(student) #after adding single element using update
student.update({'Marks':430, 'Age':19})
print(student)
Now that we know how to update and add new elements in the dictionary.
Let’s take a look at another most important topics which is Adding an old dictionary to another dictionary, which you can do by using update() method.
For example – if you have 2 dictionary named ‘student’ and ‘contact’ and you want to add the elements of ‘contact’ dictionary to the ‘student’ dictionary. Then you can do so as follow:
Hope you like the article on Adding to Directory in Python. We have also created an article on Python Projects for Beginners, which you must take a look.