Lesson 6: Nested Data in Python

Nested data is simply data structures that make saving, collecting, accessing, accumulating data more sensible sometimes.

It’s not a very complicated topic and nested data usually rather simplifies the representation and handling of data. We will go through some of the most common nested data examples in this lesson.

  • List outside
    • List inside
    • Dictionary inside
  • Dictionary outside
      • List inside
      • Dictionary inside

Let’s see some examples.

Used Where?

Nested Data can make accessing, accumulating, collecting, parsing, saving, reading data more sensible.

You can come across nested data situations in very simple data form such as small sized lists in your program or you can also encounter more complex or bigger size examples in web and computer applications such as:

  • APIs
  • Databases
  • Other data collection tools
  • Softwares
  • Games

Syntax do(s)

1) Simply data syntax is followed whether its lists or dictionaries involved. And as always strings are represented inside quotes.

Syntax don't(s)

1) na

Example 1: Accessing inside Nested Data

Nested Data can come in combinations of data structures. It can be lists inside dictionaries or dictionaries inside dictionary etc. So, when accessing elements of nested data you will have to assess the situation and access a nested data’s elements according to their data types and structures. Trial error is often a common strategy when dealing with big nested data as well.

Let’s start with some simple examples. We will try to access the last list inside another list:

nested_lst1 = [[1,2], ["Venus","Mars"], [True, False]]
print(nested_lst1[2])

[True, False]

That was an easy one.

Example 2: Accessing innermost elements in Nested Data

And then we can access the elements of an inner list using an index chain as following:

nested_lst1 = [[1,2], ["Venus","Mars"], [True, False]]
print(nested_lst1[2][0])

True

Example 3: Dictionary nested inside a list

Often we see dictionaries inside a list or lists inside a dictionary as it can be very convenient to store data in this structure.

We can simply access dictionaries using list’s index.

nested_lst2 = [{"camera":2, "phone":1}, {"car":1, "van":0}]
print(nested_lst2[0])

{‘camera’: 2, ‘phone’: 1}

Tips

  1. Star notation can be used to unpack sequences in Python such as lists, tuples and dictionaries.
  2. It is used with an asterisk before the collection. If collection’s each element consists of two values such as in dictionary example where we have key:value pairs as dictionary’s items, we have to use double asterisk notation:
    1.  *list
    • **dict
  • This practical unpacking method can be particularly useful when working with nested data.

Example 4: Unpacking nested data with star notation (asterisk operator)

You can also unpack a nested list or tuple by using star notation in Python. This is performed by using an asterisk operator (*) before the collection as following:

nested_lst1 = [[1,2], ["Venus","Mars"], [True, False]]
print(*lst1)

[1,2], [“Venus”,”Mars”], [True, False]

Function : zip

zip function can be used to match items of separate collections in Python. More about Python zip function here.

Example 5: Nested data, star notation and zip function

You can also combine star notation with zip function to access nested data.

nested_lst1 = [[1,2], ["Venus","Mars"], [True, False]]

lst_T = zip(*lst1)

print(list(lst_T))

[(1, ‘Venus’, True), (2, ‘Mars’, False)]

Example 6: Accessing a dictionary inside a list

Accessing inner elements second example:

nested_lst2 = [{"camera":2, "phone":1}, {"car":1, "van":0}]

print(nested_lst2[1]["car"])

1

Such structures are more common than expected and they can be encountered when collecting data from APIs, Web Scraping, Archives and Databases. Also other popular data formats such as Json use nested data heavily and it can be encountered anywhere from data science and machine learning to quantitative trading to game development.

Example 7: Two Level Deep Nested Data

In this example outermost container is a list and we will access a dictionary inside a dictionary that’s inside that list and then we will access the key “color“.

nested_lst3 = [{"camera":{"color": "black", "res": 16}, "phone":1}, {"car":{"amount": 1, "year": 2017, "color": "red"}, "van":0}]

print(nested_lst3[1]["car"]["color"])

‘red’

Example 8: Two Level Deep Nested Data

Here is a 2 level nested dictionary access. We will be accessing the items of a dictionary inside another dictionary

nested_lst4 = {"items": {"camera":{"color": "black", "res": 16}, "phone":1}, "assets": {"car":{"amount": 1, "year": 2017, "color": "red"}, "van":0}}

print(nested_lst4["assets"])

{‘car’: {‘amount’: 1, ‘year’: 2017, ‘color’: ‘red’}, ‘van’: 0}

Perfect!

Accessing nested data summary

Above examples can seem complicated at first glance but really the idea is quite simple. use [] for accessing a list or dictionary item. if you’re accessing a list element type its index number such as: [2], if it’s a dictionary value type its key in quotes such as: [“year”] and feel free to chain these notations as needed if your data is nested such as: data[1][“color”][3][“make”].

Example 9: Three Level Deep Nested Dictionary

This time an example that’s 3 level deep. Accessing a dictionary inside a dictionary inside another dictionary.

nested_lst4 = {"items": {"camera":{"color": "black", "res": 16}, "phone":1}, "assets": {"car":{"amount": 1, "year": 2017, "color": "red"}, "van":0}}

print(nested_lst4["assets"]["car"]["year"])

2017

Example 10: The whole list as key values

Here are some of the most famous women athletes in skiing and their international alpine ski competition medal counts. Unfortunately we have the values in separate Python list but thankfully they are in exact right order.

names = ["Sofia Goggia", "Mikaela Shiffrin", "Wendy Holdener", "Lindsey Vonn", "Frida Hansdotter", "Michelle Gisin", "Ragnhild Mo

for i in (zipped_lst):
    dict[i[0]] = i[1]
    
print(dict)

{‘Sofia Goggia’

Perfect!

Advanced Concepts (Optional)

1- Nested Data is a common structure for JSON format which many API applications use.

Below is nothing but some neat nested data example, but for now you don’t have to worry too much about it as we will cover these topics in greater detail later.

Here is a typical example demonstrating how your JSON may look after an API access:

Example 11: Nested Data From Json Format

If you are interested in Json format you can take a look at this Python Json Tutorial

A simple API example showing the nested data output:

req = requests.get('http://api.zippopotam.us/us/vt/rutland')
t = req.json()
data = json.dumps(t, indent=3)

print (data)

{
“country abbreviation”: “US”,
“places”: [
{
“place name”: “Rutland”,
“longitude”: “-72.9708”,
“post code”: “05701”,
“latitude”: “43.6141”
},
{
“place name”: “Rutland”,
“longitude”: “-72.9906”,
“post code”: “05702”,
“latitude”: “43.4128”
},
{
“place name”: “Center Rutland”,
“longitude”: “-73.017”,
“post code”: “05736”,
“latitude”: “43.6023”
},
{
“place name”: “West Rutland”,
“longitude”: “-73.0424”,
“post code”: “05777”,
“latitude”: “43.5781”
}
],
“country”: “United States”,
“place name”: “Rutland”,
“state”: “Vermont”,
“state abbreviation”: “VT”
}

Here we are seeing a parent dictionary which has a key named places which has a list as its value and this list consists of multiple dictionaries as well.

That will be it for this lesson. We have learned Nested Data and demonstrated plenty of Python examples that cover different types of Nested Data and its applications.

I hope it was a useful lesson. We’ve also prepared Python Nested Data exercises which you may find below.

Next lesson will introduce Python conditional statements (if, elif, else) with examples. It’s an exciting and extremely fundamental programming concept that will hopefully be beneficial to pursuers of Python programming skills like yourself.

Next Lesson: Conditionals