This process is continued till the loop reaches i=3 which is the last iteration. 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. 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. This for loop is used to produce an inner dictionary that contains the square elements of the current number through 4. We can modify the above example to get a slightly better output.Įverything is the same as the above example except the inner for loop which uses an increment i+4. What if we can change the values of the inner dictionaries too? Nested Dictionary With Different Values for Different Keys The squared values remain the same for different keys. If you observe the output, we can find the same set of dictionaries for different keys. Nested Dictionary Using A Simple For Loop Lastly, we are printing the nested dictionary which has square values of all the numbers from 0 to 4. Outside of the inner loop, we are assigning the inner dictionary to the current value of the outer dictionary. Inside this loop, for each value in the range of 4, the square of the number is generated. We have another for loop which also executes four times. Inside this loop, we are creating an inner dictionary that is also empty. Next, we are initializing a for loop which runs four times. In the first line, we are initializing an empty dictionary that is used to store the whole nested dictionary. Let us see an example of a simple dictionary. A dictionary might help you in such situations. Imagine you are grocery shopping and you want to store all the items of different categories in one list. Visit this article to understand sorting dictionaries. Duplication is not allowed in dictionaries. A dictionary is mutable which means its elements can be deleted, updated, and even new elements can be added to it after creation. Dictionary ExplainedĪ dictionary is a data structure of python that stores data in the form of ‘key: value’ pairs. If you want to know more about dictionaries in python, you might want to check this out.īefore we move on to creating a nested dictionary using a for loop, we need to first know about dictionaries and nested dictionaries. To define, a nested dictionary is a collection of one or more other dictionaries in it.Ĭreating 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.Īfter 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. A nested dictionary may have as many dictionaries inside it as possible.
0 Comments
Leave a Reply. |