Learn about Nested Dictionary in Python. Show
You must be familiar with dictionaries in Python. However, before moving ahead with the agenda of our article, let us get a quick recap of the dictionary in Python. Dictionary in Python is one of the most popular data structures. Dictionaries are used to store data in a "key-value" pair format. The keys are always unique within a dictionary. The values of the Python dictionary may or may not
be unique. We can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value. So, what are Nested Dictionaries?In Python, a nested dictionary is a dictionary inside a dictionary. Basically, it is a collection of dictionaries kept inside a single dictionary. Nested dictionaries are one of the ways to represent and store structured information (similar to some ‘records’ in other languages). Below given is a simple example of a nested dictionary.
We shall understand the above code in depth going further. Creating a Nested DictionaryCreating a nested dictionary is very similar to how we create any other normal dictionary. There is a very basic difference that, in the nested dictionary, the value can also be a dictionary. Let us understand this clearly through an example. Suppose, we have kept the records of 3 students in a dictionary. Say, an individual student has the following properties: Name, Class, and Roll No. We can represent this very clearly through a nested dictionary.
Explanation: In the above example, we have created a dictionary named "school". This is a nested dictionary which has the student index as the key and the student's properties like name, roll and class are the values of the keys. But here, please note that every key is mapped to a value which itself is a dictionary. In simple words, the values in this dictionary are the dictionary itself. So, this is how we create a nested dictionary. Let us also learn about an important way of creating nested dictionaries. The dict() ConstructorThere is a "type constructor" called dict() in Python, that can be used to create python dictionaries from keyword arguments or any kind of key-value pairs. It can even create a dictionary from another dictionary and keyword arguments. These terms might not be making any sense to you, hence let us understand how is the dict() constructor used to create a nested dictionary through easy examples. 1. Keyword Arguments to Nested DictionaryTo create a nested dictionary, we can simply pass our dictionary key : value pair as keyword arguments to the dict() constructor. For example, look at the code below --
Output:
In the above example, please note that we have enclosed our dictionary into round brackets '()' and passed it to the dict() constructor --
As a result, the dict() constructor transformed the above keyword arguments into nested dictionary. 2. Using zip() Method in PythonThe zip() function takes some iterables (can be zero or more), sums them up in a tuple, and return them. We can use zip to combine separate lists of keys and values. We can also pass the list of keys and values to the zip() function dynamically at runtime.
Output:
3. Using Python Dictionary fromkeys() MethodThe fromkeys() method in python dictionary creates a new dictionary with the default value for all specified keys. In case we do not specify any default value then, all the keys are set to None. Code:
Output:
We can use the dict.fromkeys() method to create a nested dictionary with some default values. For example, consider the given code below -- Code:
Output:
Explanation: As we explained above, the fromkeys() created a dictionary based on the keys and default the values we passed to it. Access Nested Dictionary ItemsWe can access the items of a dictionary by specifying the key of the dictionary and key of the nested dictionary into square brackets. For example, consider the below code: Code:
Output: Exception: If we try to access any key-value pair that doesn't exist in our dictionary, we will get a keyerror. Code:
Output: However, we can prevent our codes to fall into any key error. This can be done using the special dictionary get() method. The get() method returns the value for the key if the key is in the dictionary, otherwise, it returns None. Hence, we never get the keyError if we use this method. Code:
Output: Deleting Dictionaries from a Nested DictionaryDeleting a dictionary from a nested dictionary is a straightforward operation, for which, we can use python's del keyword. Another way to delete a dictionary is, by using the pop() method in python. 1. Using the pop() Methodpop() is generally used when we want the value of the dictionary after deleting it. So, pop() returns a value. For example, look at the code below: Code:
Output:
2. Using del KeywordAnother way to delete a dictionary is by using del keyword in Python. This is generally used when we do not want the value which is deleted. For example, look at the code below: Code:
Output:
Add or Update Element to a Nested DictionaryWe can add or update the elements of a nested dictionary very simply. However, there is a difference when we are trying to add a new key to our dictionary or update any existing key. The difference is --
Let us understand these in-depth below through code. If we add a key-value pair to a nested dictionary, with a key that is already present into the original nested dictionary, then the old value gets updated. For example, look at the code below: Code:
Output:
Explanation: In the above example, we try to add an element to the dictionary, but please note that the key already exists in our dictionary. Since the key is already present in the dictionary, its value is replaced by the new one. Let us now see by adding a new element to our dictionary. Code:
Output:
In this example, we have used a new key so it directly gets added to our nested dictionary. And, hence the dictionary has a new element added. So this is a major difference, if our key already exists in our dictionary then our dictionary gets updated, otherwise, a new key-value pair is added to the dictionary. Delete Elements from a Nested DictionaryWe have already seen how to delete a dictionary item from a nested dictionary. Here we will learn how can we remove a single element or value from a nested dictionary. Removing value from a nested dictionary is very similar to removing a dictionary item itself. There are mainly 2 ways(precisely 3). Let us learn each of them. Using del Keyword in PythonWe can use the del keyword to delete an element from our nested dictionary. However, del does not return anything hence we cannot retrieve the element which we have deleted using it. Let us see an example to demonstrate its usage. Code:
Output:
Explanation: In the above example, we used the del keyword to delete the value from the dictionary. We fetched the value of the dictionary using the key. We can also use indexing to delete elements at any particular index. Using pop() MethodWe can use the pop() method to delete an element from our nested dictionary. Unlike the del keyword, pop() returns the value whenever it deletes any item. So, it is recommended to use the pop() method whenever we want to fetch the value of the element we deleted. Below given is an example of using pop to delete elements. Code:
Output:
Explanation: As explained above, we fetch the dictionary elements values to be deleted using the key of the nested dictionary. Later, we store the values of the elements that are popped using pop(). Iterate through Each Element in a Nested DictionaryIn normal dictionaries, we can iterate over the dictionary using dict.items(). But, this is not the case with nested dictionaries. Here, we can have dictionaries within dictionaries and hence we have to go to one more level for iterating through their values. We can iterate in a nested dictionary using the nested for-loop. Let us look at our code to understand it better. Code:
Output:
Explanation: In the above example, we first iterate over the dictionary items, which in turn gives us the key value pair keykey, valval . Now, the resulting value valval is another dictionary. Hence, we iterate over val.items() to get nestedKeynestedKey and neste dValnestedVal. This code will work fine if we have only one level of nested dictionary. For n-levels of the nested dictionary, this is not the appropriate way. In this article, we learned how can we iterate over a nested dictionary which is 1 level nested (only 1 dictionary inside a dictionary). However, there are cases where we might have n-levels of nested dictionaries. For them, the simplest way to iterate is through recursively calling it's each level of nesting. Please note, that the n-level nested dictionary is not under the scope of this article. Merge Two Nested DictionariesTwo nested dictionaries can be merged using the update() method in Python. update method():The update() method updates the dictionary with the key: value pairs from the element.
Syntax:
Let us see the code below to update any dictionary. Code:
Output:
Explanation: In the above example, we update the my_dict1 dictionary with my_dict2 dictionary. While doing so, whichever key is already present in my_dict1 gets overwritten by key of my_dict2. And, if the key is not present, then a new key gets added. For example, BB key gets updated in the my_dict1 dictionary. And new key DD is added in my_dict1, because it was not already present. Important conclusions:
Link to Other Similar Articles --This article included all the major points you need to know to get a brief idea about nested dictionaries in Python. You may also refer to the below scaler articles to know more about Dictionary in Python. Also, the prerequisite to this article is dictionary in Python.
ConclusionIn this article, we learnt about nested dictionaries in Python. Let us recap what we learned throughout.
How do you get a specific value from a nested dictionary in Python?Access Values using get()
Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).
How do I extract a dictionary value?How to Extract Dictionary Values as a List. (1) Using a list() function: my_list = list(my_dict.values()). (2) Using a List Comprehension: my_list = [i for i in my_dict.values()]. (3) Using For Loop: my_list = [] for i in my_dict.values(): my_list.append(i). How do you make a nested dictionary dynamically in Python?Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.
What is nested dictionary in Python?In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.
|