Nested Dictionaries

Summary : Read a JSON file, create a Dict, loop through and get keys and values from the inner Dict using Python.

uses : f.read / json.dumps / json.loads / list comprehension / for loop
Start with a JSON file – which looks like this in Notepad….

This post assumes you already have a nested dictionary saved as a JSON file.

We want to do 3 things:

  1. Import the JSON into a Dict type object

2. Display the Dict to check the format

3. Loop through the Dict to get the values that we need to print out.

Let’s get started,

Import the JSON file

First we need to use “import json” to work with the json format

Next, open the file “ytdict.json” and load it into an object

with open("ytdict.json") as f:
d = json.loads(f.read())

print(type(d)) # will give : <class 'dict'>

Check the contents, sort by int, otherwise 11 will appear before 2

Print the contents

print (json.dumps({int(x):d[x] for x in d.keys()}, indent=2, sort_keys=True))

The output should look like this :

Here you can see the outer dict, and then the inner dict with 2 key:value pairs

For loop with Nested Dictionaries

Write a new file, which will be the one we want to use as our actual program; ‘demo_nested_dict.py’

import json
# The 'real' code used in ytapithumbget.py
with open("ytdict.json") as f:
    data = json.loads(f.read())
    # nested dictionary needs 2 for loops
    for k,v in data.items():
        for v2 in v:
        	print (v2[1])
        	print("------------")

We loop through the outer dictionary, finding the key:value pairs, and then using the second for loop we iterate through the key:value pairs from the returned values of the outer dictionary.

Note the index of [1] – That picks out the values from the values in the first for loop.

If we had used [0] we would have ended up with this:

Iterating through Nested Dictionaries | JSON – watch the YouTube Video

Python Code

Next article

Scrapy : Yield