Hello peeps! Welcome to the new episode of the Python tutorial. We have been working with different types of data collection in Python, and it is amazing to see that there are several ways to store and retrieve data. In the previous lecture, our focus was on the basics of dictionaries. We observed that there are many important topics in the dictionaries, and we must know all of them to make our base of concepts solid. For this, we are now dealing with the dictionaries in different ways, and this tutorial is going to be very interesting because we will pay more heed to the practical work and, by choosing a few cases in our codes, we will apply multiple operations to them. So have the highlights of today’s learning, and then we will move forward with the concepts.
What are nested dictionaries, and how do we use them?
How do you access the elements in the nested dictionary?
Tell us the procedure to add and delete elements from the dictionary.
Can we modify the elements of the dictionary? If yes, then how can we do so?
What is the membership test, and what is the procedure to use it in the dictionary?
Write the simple example in which the iteration is used with the dictionary.
Nested Dictionaries in Python
In the previous lecture, we saw simple dictionaries and applied their functions to them. In the present lecture, the details of the dictionaries will be discussed in detail. These functions are not new to us but have been learned while dealing with sets and lists. Yet, the working and the results of every function are different with different types of data, and therefore, we are using the predefined functions again but with a twist. In the previous lecture, we saw the nested dictionary in an example but have not mentioned the details because we were discussing the list in dictionaries and it was not suitable to discuss it at that moment. Yet, have a look at the definition of a nested dictionary:
“A nested dictionary is a type of dictionary in Python that contains more than one dictionary separated by commas in it with different indexes, and each dictionary has a specific number according to its order.”
Accessing the data is a little bit more difficult in the nested dictionaries than in the simpler ones because the index is so important. The dictionaries are then divided with the help of commas between them. Open your Jupyter notebook by following these steps:
Go to the search bar on your PC.
Search for the Jupyter notebook.
Now go to the drop-down menu and choose Python there.
Wait for the new local host to be opened in your browser.
Go to the new cell and start coding.
Copy this code and paste it into the cell. By pushing the run button, you will get the perfect nested dictionary.
Accessing the Data From a Nested Dictionary
Do you know the meaning of our statement that accessing the data from a nested dictionary is a little bit different? It is because we need to type more of the data, and therefore, it is important to mention all the information accurately, as with all types of data, and this becomes tricky for non-programmers.
#Declaring the nested dictionary containing the information of the books in a library
bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': '125'},
2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': '234'},
3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': '564'}}
#Printing the required value
print("Your required data = ", bookData[2]['coverColor'] )
So, as you can see, the real use of a nested dictionary is to get more readable and clean data every time. These are the advantages of the nested dictionary it is more practical, and a large amount of data can be stored and accessed easily.
Addition of The New Element in Nested Dictionary
It is the plus point of the dictionary that programmers can easily add the element in the nested dictionary by using some simple steps. The point here is to e discussed is to show you that the concept of an empty dictionary is present in Python. Many other data types do not have this characteristic. Hence, the addition of a new element becomes easy while using the dictionary. Have a look at the output of the code and after that, we will discuss the points about it.
#Declaring the nested dictionary containing the information of the books in a library
bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},
2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},
3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}
print("Dictionary before modification = ",bookData )
print()
#Making the room for the new element by creating the empty dictionary
bookData[4]={}
#inserting elements in the next space
bookData[4]['subjectName']= 'English'
bookData[4]['coverColor']= 'yellow'
bookData[4]['Pages']= 611
print("The modified dictionary= ", bookData)
We can conclude the following points from the data given above:
The addition of the new dictionary to the existing nested dictionary is easy.
There is a need for a blank element so that we may fill in the required items.
The programmer in the code has declared the number of the dictionary and not the index, therefore, the data is not started with a zero and instead, the numbers of our choice are used. The programmer may name its dictionary anything no matter if it is the number of the alphabet.
Deleting the Dictionary from Nested Dictionary
Let us discuss the case in which the programmer wants to delete the whole dictionary from the nested collection for some reason. For this, the procedure is not too long and the simple delete command is used for it. For better elaboration, we are using the same example and deleting the second dictionary from our list.
#Declaring the nested dictionary containing the information of the books in a library
bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},
2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},
3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}
print("Dictionary before modification = ",bookData )
print()
#Deleting the 2nd dictionary
del bookData[2]
print("The modified dictionary= ", bookData
Here, the question arises if the single element is to be deleted only, what will be the code? There are only minor changes in the code given above, and only the particular element of the mentioned dictionary will be deleted.
#Declaring the nested dictionary containing the information of the books in a library
bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},
2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},
3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}
print("Dictionary before modification = ",bookData )
print()
#Deleting the specific elements from the dictionary
del bookData[2]['coverColor']
del bookData[3]['subjectName']
print("The modified dictionary= ", bookData)
Modifying Data From Dictionary
The next step is to learn about the modification process of the dictionary, and for that, we are choosing another example because it is boring to check the conditions from the same example all the time. For the sake of simplicity, we are using the simple dictionary instead of the nested type of the dictionary.
#Declaring the initial data of the staff
staffInfo = {"2C32": "HR", "2C34": "Chemist", "2C20": "Doctor"}
print("Initial Staff Information: ", staffInfo)
#Changing the staff information
staffInfo["2C32"] = "Compounder"
#Printing the results
print("Updated Staff Information: ", staffInfo)
Hence, in this way, we do not have to first delete and then add the new element in its place; simply changing the element is enough. The new value is masked over the previous one, and in this way, the task becomes easy.
Membership Test on the Dictionary
Until now, we have seen some simple and short examples so that the concepts may be easily understood. Yet you must know that in real-life applications, dictionaries are so large that it becomes difficult to notice the existence of specific elements in them. For such cases, it is important to learn the command to check the availability.
# Membership Test for our new dictionary
AvailableFood = {1: "chicken", 2: "beef", 3: "barbeque", 4: "burger", 5: "soup",
6: "salad", 7: "cake", 8: "lasagna", 9: "pizza", 10: "pie",11: "sandwiches",
12: "pasta", 13: "mushrooms", 14: "sausage", 15: "ice cream", 16: "cola", 17: "cupcakes",
18: "chocolate", 19: "biryani", 20: "golgappy", 21: "bread", 22: "jam", 23: "eggs" }
#Checking the availability by using just the key
print(6 in AvailableFood)
#checking if the certain key is "not" available
print(18 not in AvailableFood)
#Using a false value to check the behaviour of the keyword
print(49 in AvailableFood)
If we go into the details of this code, we may get the idea that:
Dictionaries can be used to store a massive amount of data.
The addition of the data is so simple and uncomplicated, and we can access any element easily.
The keys are useful to get the data easily without any complexity in typing in such cases if we use the integers as keys.
The “in” function searches for the required elements of the user and gives the result about the availability of the element.
The “not in” function is totally opposite from the former case, and the programmer can use it to check whether the specific element is absent or not.
The third case is interesting, we simply put the value to check how the “in” function responds when the element is not present in the dictionary, and the result was as expected.
Using the Iterations in Dictionary
The iteration process is fascinating, and we always try to provide you with examples that you will use in the practical implementation over and over again. The iterations are an important concept, and you will learn them in detail in the coming sessions, but we believe that, for now, you have an idea of what they are and how the programmers use them in their codes. It is time to check what the dictionary will do if we use it in the for loop.
# Membership Test for our new dictionary
AvailableFood = {1: "chicken", 2: "beef", 3: "barbeque", 4: "burger", 5: "soup",
6: "salad", 7: "cake", 8: "lasagna", 9: "pizza", 10: "pie",11: "sandwiches",
12: "pasta", 13: "mushrooms", 14: "sausage", 15: "ice cream", 16: "cola", 17: "cupcakes",
18: "chocolate", 19: "biryani", 20: "golgappy", 21: "bread", 22: "jam", 23: "eggs" }
#using the for loop with the "in" keyword to get the list of each and every food item
for element in AvailableFood:
print(AvailableFood[element])
Hence, all the elements are printed one after the other in a new line, and the programmers can simply get the available food items by using a simple command.
For more practice, I want to check the behaviour of this loop when I use it with the nested dictionary:
#Declaring the nested dictionary containing the information of the books in a library
bookData = {1: {'subjectName': 'Physic', 'coverColor': 'red', 'Pages': 12},
2: {'subjectName': 'Chemistry', 'coverColor': 'blue', 'Pages': 234},
3: { 'subjectName': 'Biology', 'coverColor': 'green and blue', 'Pages': 564}}
print("Elements of the dictionaries = ",bookData )
print()
#printing All the dictionaries using iteration.
for myBooks in bookData:
print("Elements of single dictionary using the for loop = ", bookData[myBooks])
The results of the code given above are clean and more understandable:
Hence, the use of iterations makes our output uncomplicated and ordered. So it was all about the dictionary in this episode of the Python programming language. It was amazing to see the different examples, and all of them were related to the dictionaries. The usage of the dictionary in Python is important to understand; therefore, we used the Jupyter notebook to access, add, delete, and modify the elements of nested dictionaries and simple dictionaries with the help of examples. Moreover, the membership test was also interesting to learn and easy. In the end, the iterations made our work easy, and we got a cleaner output with the help of the iterations. We hope it was an attractive way to learn the dictionaries and stay with us for more concepts of Python. Happy learning to all of you.