What is nested data in python?

 In simple term, data within the data is generally called a nested data.

A list within a list or a table within a table are examples of nested data.

Imagine a complex and extensive codes. You can understand that at times it is difficult to understand it quickly. Hence, a good practice is to divide in to smaller groups and find their meaning so gradually you can start unwrapping the whole code.

One simple example is the nested dictionary data.


Now we can add a list within this dictionary to make it a nested data

We are adding cathy under kids.


So now this becomes a nested data. List within dictionary.

And now since kids is a list, we can apply all functions that are applicable to list in order to access data within this list.

In this dictionary, there are key-value pairs. dad is a key and value is john. Similarly kids is a key and it has 2 values peter and cathy. So length of this dictionary is 3 as there are 3 key-value pairs.


We can access values within the key kids and it will show below results.


since kids is a list, we can also use index function to select values within the list. If we want to find the boy within the family, then we can write the below code.


This is a simplistic example but when in a complex code, we are not sure about the type of data within the data we can use type function to reveal it.




Now we know that it is a list and so we can apply all functions that can be applied to any list. This way, selecting values from within the nested data becomes easier.

To find number of kids in a family:

Let's say that there is an arrival of a new born within this family and we want to add it. Since kids is a list, we can append it just like any other list.



As you can see tara is added in the family.

Let's say we want to get first character of kids names in capital letter.
Simple way to do this would be:


And the same thing can also be accomplished in a bit fancy and concise way would be:


Yet another way to accomplish the same result using for loop:



As you can see that using for loop, 3 line code was reduced to 1 line.
But there is no right or wrong method of coding. Whichever way is more convenient and easily understandable, we can use it.







No comments:

Post a Comment

Complex query example

Requirement:  You are given the table with titles of recipes from a cookbook and their page numbers. You are asked to represent how the reci...