How to Create a Nested Dictionary via for Loop?

How To Create Nested Dictionary Via For Loop

A nested dictionary is used to store any data in a hierarchical format. A nested dictionary may have as many dictionaries inside it as possible. To define, a nested dictionary is a collection of one or more other dictionaries in it.

Creating a nested dictionary using a for loop might sound like a new concept but it is an easier and much more systematic approach to create a nested dictionary using a for loop which can then be used to loop through the nested data structure.

After a dictionary is created using a for loop, another for loop may be used to iterate through the dictionary and access elements of the dictionary.

If you want to know more about dictionaries in python, you might want to check this out.

Before we move on to creating a nested dictionary using a for loop, we need to first know about dictionaries and nested dictionaries.

Dictionary Explained

A dictionary is a data structure of python that stores data in the form of ‘key: value’ pairs. A dictionary is mutable which means its elements can be deleted, updated, and even new elements can be added to it after creation. Duplication is not allowed in dictionaries.

Visit this article to understand sorting dictionaries.

Imagine you are grocery shopping and you want to store all the items of different categories in one list. A dictionary might help you in such situations.

Let us see an example of a simple dictionary.

grocerylist={'Fooditems':['Apple','Banana','Broccoli','Chips','Dates']}
print("The example dictionary is:",grocerylist)

In the above code, we are creating a variable called grocerylist to store the dictionary. The dictionary contains a key Fooditems that has the values associated with it enclosed in square brackets. The values are Apple, Banana, Broccoli, Chips, and Dates.

In the next line, we are printing the above dictionary.

Dictionary
Dictionary

What Is a Nested Dictionary?

As we have seen a dictionary in the above example, a nested dictionary can consist of many such dictionaries inside it.

Let us take the same example. Imagine you want to add even more categories to the grocerylist you wish to buy. That will make it a nested dictionary, isn’t it?

grocerylist={'Fooditems':['Apple','Banana','Broccoli','Chips','Dates'],
             'Drinks':['Milk','Chocolate Mix','Apple Juice','SoftDrinks'],
             'HouseholdItems':['Candles','Cutlery','Stationery','Sanitizer']
             }
print("The example dictionary is:",grocerylist)
print(type(grocerylist))

Adding to the Fooditems, we have Drinks and HouseholdItems. So now, the dictionary grocerylist has three dictionaries inside it.

Let us see the output.

Nested Dictionary
Nested Dictionary

Now before we move on to creating nested dictionaries with for loop, let us first understand what a for loop is.

Syntax of for Loop Explained

A for loop is used to iterate( run through) a sequence of elements. A for loop can be used to iterate through a list, a tuple, a string, and even a dictionary.

The for loop follows the syntax:

for item in sequence:
                    block of statements

Here, the word item is used as a variable to run through every element in the sequence.

The sequence is the data structure in which we wish to iterate.

Also Read: For Loop with Two Variables in Python

Let us see an example that prints the square of each number using for loop.

n=int(input("Enter the number:"))
for i in range(n):
  print("The square value of",i, "is:",i**2)

In the first line, we are accepting a raw input(input from the keyboard). This value is stored in a variable called n.

In the next line, we are initializing a for loop that runs through every number till n. So if n is given as 5, the code will execute five times.

In the loop, we are using a print function that prints the square of the number in the range of n.

For Loop Example
For Loop Example

Let us now look at a few examples of creating a nested dictionary using for loop.

Create a Nested Dictionary via for Loop

Let us look at all the possible approaches to creating a nested dictionary using a for loop.

Simple for Loop to Create a Nested Dictionary

In this example, we are going to see a nested dictionary that contains the square of elements for different keys.

odict = {}
for i in range(4):
    idict = {}
    for j in range(4):
        idict[j] = j**2
    odict[i] = idict
print(odict)

In the first line, we are initializing an empty dictionary that is used to store the whole nested dictionary. This dictionary is named odict.

Next, we are initializing a for loop which runs four times. Inside this loop, we are creating an inner dictionary that is also empty. This dictionary is called idict.

We have another for loop which also executes four times. Inside this loop, for each value in the range of 4, the square of the number is generated.

Outside of the inner loop, we are assigning the inner dictionary to the current value of the outer dictionary.

Lastly, we are printing the nested dictionary which has square values of all the numbers from 0 to 4.

Nested Dictionary Using A Simple For Loop
Nested Dictionary Using A Simple For Loop

If you observe the output, we can find the same set of dictionaries for different keys. The squared values remain the same for different keys. Which is kind of boring to look at. What if we can change the values of the inner dictionaries too?

Nested Dictionary With Different Values for Different Keys

We can modify the above example to get a slightly better output.

odict = {}
for i in range(4):
    idict = {}
    for j in range(i, i + 4):
        idict[j] = j**2
    odict[i] = idict
print(odict)

Everything is the same as the above example except the inner for loop which uses an increment i+4. This for loop is used to produce an inner dictionary that contains the square elements of the current number through 4. So if the loop is at 0 currently, it will create the dictionary that contains the squares of 0,1,2, and 3 for the key 0.

If the loop is at the second iteration(i=1), the dictionary contains the square values of numbers including 1,2,3,4 for the key 1.

This process is continued till the loop reaches i=3 which is the last iteration.

Nested Dictionary With Different Values
Nested Dictionary With Different Values

Using defaultdict to Create a Nested Dictionary

The same example can also be written in a different way. Sometimes when we are creating a dictionary, it might raise a KeyError when any key is missing. In such cases, we can use defauldict which is a subclass of the dict class. This container creates a default value for the missing one and hence, avoids any error.

Read this article to understand defaultdict.

from collections import defaultdict
odict = defaultdict(dict)
for i in range(4):
    for j in range(i,i+4):
        odict[i][j] = j**2
print(odict)

We are importing the defaultdict container from the collections module.

In the net line, we are creating an outer dictionary called odict with the help of defaultdict.

Next, we are initializing an outer loop that executes four times.

We are also initializing an inner loop that iterates for i+4 times which means, if i=0, this loop results in the square of 0,1,2,3.

Lastly, we are printing the nested dictionary.

Nested Dictionary using defaultdict
Nested Dictionary using defaultdict

Let us try to make this a little bit more interesting. Let us take raw input from the user and then create a nested dictionary.

Creating a Nested Dictionary With User’s Input

Let us create a nested dictionary with the person’s details. But, let us take all the input from the user and organize the data into a nested dictionary with for loop.

import pprint
data = {}
n=int(input("Enter number of levels: "))
status=""
for i in range(n):
  name = input("Enter person {}'s name: ".format(i+1))
  age = int(input("Enter that person's age: "))
  address = {}
  address["street"] = input("Enter the street name: ")
  address["city"] = input("Enter the city name: ")
  address["state"] = input("Enter the state: ")
  address["zip"] = input("Enter the zip code: ")
  data[name] = {"name": name, "age": age, "address": address}
  status = input("Do you want to continue? Answer with yes/no: ")
  if status == "no":
    break
pprint.pprint(data)

Firstly, we are importing the prettyprint module to be able to print the nested dictionary in a formatted manner.

Next, an empty dictionary named data is created to contain the nested dictionary.

In the third line, we ask the user to specify the number of people to include. This is the value stored in n. This input iterates through the for loop.

Next, we create a string of flags that will indicate when to end.

In the following line, we initialize a for loop that runs until n.

Within this cycle, we prompt the user for the individual’s name and age.

name = input("Enter person {}'s name: ".format(i+1)): This line is used to print the name of person 1. The value of ‘i’ will alter with each iteration.

Next, we create a dictionary called address that will store the address details of the person.

This dictionary will contain the street name, city name, state, and zip code.

The status is used if the user wants to stop giving input. They can enter either yes or no when asked. When the answer is no, the computer stops asking for input and the loop is terminated.

Lastly, we print this huge nested data using pprint function.

Nested Dictionary With User Input
Nested Dictionary With User Input

Conclusion

To conclude, we have learned what a dictionary is and have seen a grocerylist which contains shopping items as keys and values as an example of a dictionary.

Next, we have also understood what is a nested dictionary. A nested dictionary may contain other dictionaries inside it. We have extended the grocerylist to make it a nested dictionary.

Before we discussed creating a nested dictionary via for loop, we explored the syntax of for loop and understood its usage by printing the square of elements in a certain range.

In the first example of creating a nested dictionary using for loop, we have seen how to create a nested dictionary that consists of the squares of the elements starting from the key. If the key is 0, that nested dictionary would have the values 0:0,1:1,2:4……. We observed that for different keys, this code prints the same inner dictionary.

In the next example, we have tried to modify the above example and print different values in the inner dictionaries.

In the third example, we have gone for a new approach called defaultdict. We have taken the same example as before but applied defaultdict on it.

Lastly, we tried to create a nested dictionary with the user’s input where the user has the choice to terminate the loop.

References

To know more about the container used in the third example(defaultdict), check out the official python documentation.