Skip to content

Nested Dictionary

diagram copy() copies the container, not what is inside it mermaid
A shallow copy makes a new outer object whose slots point at the very same inner objects. For a flat structure that is a full copy. For anything nested it is not -- and mutating an inner value through either name shows up in both, because there is only one inner value.

Nested dictionaries are dictionaries that contain other dictionaries.

dict_nested.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
print(data)

Output:

command
C:\Users\username>python dict_nested.py
{'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}

In this example, we declare a dictionary and assign it to the variable data. We then print the variable data. The output shows that the variable data is a dictionary.

Accessing nested dictionaries is a way to access the values of a nested dictionary.

dict_nested_access.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
print(data['a']['b'])
print(data['d']['e'])

Output:

command
C:\Users\username>python dict_nested_access.py
1
3

In this example, we declare a dictionary and assign it to the variable data. We then print the variable data. The output shows that the variable data is a dictionary.

Accessing Nested Dictionaries Using get() Method

Section titled “Accessing Nested Dictionaries Using get() Method”

Accessing nested dictionaries using the get() method is a way to access the values of a nested dictionary.

dict_nested_get.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
print(data.get('a').get('b'))
print(data.get('d').get('e'))

Output:

command
C:\Users\username>python dict_nested_get.py
1
3

In this example, we declare a dictionary and assign it to the variable data. We then print the variable data. The output shows that the variable data is a dictionary.

Looping through nested dictionaries is a way to iterate through the keys, values, or items of a nested dictionary.

dict_nested_loop.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
for key, value in data.items():
    print(key, value)

Output:

command
C:\Users\username>python dict_nested_loop.py
a {'b': 1, 'c': 2}
d {'e': 3, 'f': 4}

In this example, we declare a dictionary and assign it to the variable data. We then loop through the dictionary items using a for loop. We then print the dictionary key and value. The output shows that the dictionary items are printed.

Looping Through Nested Dictionaries Using Deeply Nested Dictionaries

Section titled “Looping Through Nested Dictionaries Using Deeply Nested Dictionaries”

Looping through nested dictionaries using deeply nested dictionaries is a way to iterate through the keys, values, or items of a nested dictionary.

dict_nested_deep_loop.py
data = {'a': {'b': {'c': 1, 'd': 2}, 'e': {'f': 3, 'g': 4}}, 'h': {'i': {'j': 5, 'k': 6}, 'l': {'m': 7, 'n': 8}}}
for key, value in data.items():
    for key2, value2 in value.items():
        for key3, value3 in value2.items():
            print("Level 1: " + key + " => Level 2: " + key2 + " => Level 3: " + key3 + " => Value: " + str(value3))

Output:

command
C:\Users\username>python dict_nested_deep_loop.py
Level 1: a => Level 2: b => Level 3: c => Value: 1
Level 1: a => Level 2: b => Level 3: d => Value: 2
Level 1: a => Level 2: e => Level 3: f => Value: 3
Level 1: a => Level 2: e => Level 3: g => Value: 4
Level 1: h => Level 2: i => Level 3: j => Value: 5
Level 1: h => Level 2: i => Level 3: k => Value: 6
Level 1: h => Level 2: l => Level 3: m => Value: 7
Level 1: h => Level 2: l => Level 3: n => Value: 8

In this example, we declare a dictionary and assign it to the variable data. We then loop through the dictionary items using a for loop. We then print the dictionary key and value. The output shows that the dictionary items are printed.

Adding nested dictionaries is a way to add a nested dictionary to a dictionary.

dict_nested_add.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)

Output:

command
C:\Users\username>python dict_nested_add.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. The output shows that the variable data is a dictionary.

Updating nested dictionaries is a way to update a nested dictionary in a dictionary.

dict_nested_update.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
data['d']['e'] = 6
print(data)

Output:

command
C:\Users\username>python dict_nested_update.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 6, 'f': 5}}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then update the nested dictionary in the dictionary. We then print the variable data. The output shows that the variable data is a dictionary.

Deleting nested dictionaries is a way to delete a nested dictionary in a dictionary.

dict_nested_delete.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)
del data['d']
print(data)

Output:

command
C:\Users\username>python dict_nested_delete.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. We then delete the nested dictionary in the dictionary. We then print the variable data. The output shows that the variable data is a dictionary.

Clearing nested dictionaries is a way to clear a nested dictionary in a dictionary.

dict_nested_clear.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)
data['d'].clear()
print(data)

Output:

command
C:\Users\username>python dict_nested_clear.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3, 'd': {}}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. We then clear the nested dictionary in the dictionary. We then print the variable data. The output shows that the variable data is a dictionary.

Copying nested dictionaries is a way to create a copy of a nested dictionary.

dict_nested_copy.py
data1 = {'a': 1, 'b': 2, 'c': 3}
data1['d'] = {'e': 4, 'f': 5}
data2 = data1.copy()
print(data1)
print(data2)

Output:

command
C:\Users\username>python dict_nested_copy.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}

In this example, we declare a dictionary and assign it to the variable data1. We then add a nested dictionary to the dictionary. We then declare a second dictionary and assign it to the variable data2. We then print the variable data1 and data2. The output shows that the variable data1 and data2 are dictionaries.

Updating Nested Dictionaries Using update() Method

Section titled “Updating Nested Dictionaries Using update() Method”

Updating nested dictionaries using the update() method is a way to update a nested dictionary in a dictionary.

dict_nested_update_method.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)
data['d'].update({'e': 6})
print(data)

Output:

command
C:\Users\username>python dict_nested_update_method.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 6, 'f': 5}}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. We then update the nested dictionary in the dictionary using the update() method. We then print the variable data. The output shows that the variable data is a dictionary.

Deleting Nested Dictionaries Using del Keyword

Section titled “Deleting Nested Dictionaries Using del Keyword”

Deleting nested dictionaries using the del keyword is a way to delete a nested dictionary in a dictionary.

dict_nested_del_keyword.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)
del data['d']
print(data)

Output:

command
C:\Users\username>python dict_nested_del_keyword.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. We then delete the nested dictionary in the dictionary using the del keyword. We then print the variable data. The output shows that the variable data is a dictionary.

Deleting Nested Dictionaries Using pop() Method

Section titled “Deleting Nested Dictionaries Using pop() Method”

Deleting nested dictionaries using the pop() method is a way to delete a nested dictionary in a dictionary.

dict_nested_pop_method.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)
data.pop('d')
print(data)

Output:

command
C:\Users\username>python dict_nested_pop_method.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. We then delete the nested dictionary in the dictionary using the pop() method. We then print the variable data. The output shows that the variable data is a dictionary.

Deleting Nested Dictionaries Using popitem() Method

Section titled “Deleting Nested Dictionaries Using popitem() Method”

Deleting nested dictionaries using the popitem() method is a way to delete a nested dictionary in a dictionary.

dict_nested_popitem_method.py
data = {'a': 1, 'b': 2, 'c': 3}
data['d'] = {'e': 4, 'f': 5}
print(data)
data.popitem()
print(data)

Output:

command
C:\Users\username>python dict_nested_popitem_method.py
{'a': 1, 'b': 2, 'c': 3, 'd': {'e': 4, 'f': 5}}
{'a': 1, 'b': 2, 'c': 3}

In this example, we declare a dictionary and assign it to the variable data. We then add a nested dictionary to the dictionary. We then print the variable data. We then delete the nested dictionary in the dictionary using the popitem() method. We then print the variable data. The output shows that the variable data is a dictionary.

Checking if nested dictionaries exist is a way to check if a nested dictionary exists in a dictionary.

dict_nested_exist.py
data = {'a': 1, 'b': 2, 'c': 3}
if 'd' in data:
    print("d exists")
else:
    print("d does not exist")
data['d'] = {'e': 4, 'f': 5}
if 'd' in data:
    print("d exists")
else:
    print("d does not exist")

Output:

command
C:\Users\username>python dict_nested_exist.py
d does not exist
d exists

In this example, we declare a dictionary and assign it to the variable data. We then check if the key d exists in the dictionary. We then print the result. We then add a nested dictionary to the dictionary. We then check if the key d exists in the dictionary. We then print the result. The output shows that the variable data is a dictionary.

Converting Nested Dictionaries to Flat Dictionaries

Section titled “Converting Nested Dictionaries to Flat Dictionaries”

Converting nested dictionaries to flat dictionaries is a way to convert a nested dictionary to a flat dictionary.

dict_nested_flat.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
flat_data = {}
for key, value in data.items():
    for key2, value2 in value.items():
        flat_data[key2] = value2
print(flat_data)

Output:

command
C:\Users\username>python dict_nested_flat.py
{'b': 1, 'c': 2, 'e': 3, 'f': 4}

In this example, we declare a dictionary and assign it to the variable data. We then declare an empty dictionary and assign it to the variable flat_data. We then loop through the dictionary items using a for loop. We then loop through the nested dictionary items using a for loop. We then add the nested dictionary items to the flat dictionary. We then print the variable flat_data. The output shows that the variable flat_data is a dictionary.

Converting Nested Dictionaries to List of Tuples

Section titled “Converting Nested Dictionaries to List of Tuples”

Converting nested dictionaries to a list of tuples is a way to convert a nested dictionary to a list of tuples.

dict_nested_list_tuples.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
list_tuples = []
for key, value in data.items():
    for key2, value2 in value.items():
        list_tuples.append((key2, value2))
print(list_tuples)

Output:

command
C:\Users\username>python dict_nested_list_tuples.py
[('b', 1), ('c', 2), ('e', 3), ('f', 4)]

In this example, we declare a dictionary and assign it to the variable data. We then declare an empty list and assign it to the variable list_tuples. We then loop through the dictionary items using a for loop. We then loop through the nested dictionary items using a for loop. We then add the nested dictionary items to the list. We then print the variable list_tuples. The output shows that the variable list_tuples is a list of tuples.

Converting Nested Dictionaries to List of Lists

Section titled “Converting Nested Dictionaries to List of Lists”

Converting nested dictionaries to a list of lists is a way to convert a nested dictionary to a list of lists.

dict_nested_list_lists.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
list_lists = []
for key, value in data.items():
    for key2, value2 in value.items():
        list_lists.append([key2, value2])
print(list_lists)

Output:

command
C:\Users\username>python dict_nested_list_lists.py
[['b', 1], ['c', 2], ['e', 3], ['f', 4]]

In this example, we declare a dictionary and assign it to the variable data. We then declare an empty list and assign it to the variable list_lists. We then loop through the dictionary items using a for loop. We then loop through the nested dictionary items using a for loop. We then add the nested dictionary items to the list. We then print the variable list_lists. The output shows that the variable list_lists is a list of lists.

Converting Nested Dictionaries to List of Dictionaries

Section titled “Converting Nested Dictionaries to List of Dictionaries”

Converting nested dictionaries to a list of dictionaries is a way to convert a nested dictionary to a list of dictionaries.

dict_nested_list_dicts.py
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
list_dicts = []
for key, value in data.items():
    for key2, value2 in value.items():
        list_dicts.append({key2: value2})
print(list_dicts)

Output:

command
C:\Users\username>python dict_nested_list_dicts.py
[{'b': 1}, {'c': 2}, {'e': 3}, {'f': 4}]

In this example, we declare a dictionary and assign it to the variable data. We then declare an empty list and assign it to the variable list_dicts. We then loop through the dictionary items using a for loop. We then loop through the nested dictionary items using a for loop. We then add the nested dictionary items to the list. We then print the variable list_dicts. The output shows that the variable list_dicts is a list of dictionaries.

Converting nested dictionaries to JSON is a way to convert a nested dictionary to JSON.

dict_nested_json.py
import json
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
json_data = json.dumps(data)
print(json_data)

Output:

command
C:\Users\username>python dict_nested_json.py
{"a": {"b": 1, "c": 2}, "d": {"e": 3, "f": 4}}

In this example, we import the json module. We then declare a dictionary and assign it to the variable data. We then convert the dictionary to JSON using the dumps() method. We then print the variable json_data. The output shows that the variable json_data is a JSON string.

Converting nested dictionaries to YAML is a way to convert a nested dictionary to YAML.

dict_nested_yaml.py
import yaml
data = {'a': {'b': 1, 'c': 2}, 'd': {'e': 3, 'f': 4}}
yaml_data = yaml.dump(data)
print(yaml_data)

Output:

command
C:\Users\username>python dict_nested_yaml.py
a:
  b: 1
  c: 2
d:
  e: 3
  f: 4

In this example, we import the yaml module. We then declare a dictionary and assign it to the variable data. We then convert the dictionary to YAML using the dump() method. We then print the variable yaml_data. The output shows that the variable yaml_data is a YAML string.

Nested dictionaries are dictionaries that contain other dictionaries. Nested dictionaries can be accessed, modified, and iterated over. Nested dictionaries can be converted to flat dictionaries, lists of tuples, lists of lists, lists of dictionaries, JSON, and YAML. For more information on dictionaries, Check out the Python Central Hub.


sketch A shallow copy duplicates the box, not the contents p5.js
Two names, one nested structure. copy() builds a new outer dictionary whose slots point at the very same inner objects, so changing an inner value through either name shows in both. deepcopy walks the whole tree and rebuilds it. Click to switch between the two and watch which arrows are shared.
pch.quizTag pch.quizDefaultTitle
  1. `orig = {'a': {'x': 1}}`; `c = orig.copy()`; `c['a']['x'] = 99`. What is `orig['a']['x']`?

    pch.quizShowAnswer

    B — `99` — Verified. A shallow copy makes a new outer dict whose slot points at the SAME inner dict, so mutating through either name is visible through both.

  2. Which of these produces an independent nested structure?

    pch.quizShowAnswer

    C — `copy.deepcopy(orig)` — Only `deepcopy` rebuilds the inner objects. `dict(orig)`, `.copy()` and `{**orig}` are all one level deep.

  3. Why is a shallow copy of a FLAT dictionary of integers perfectly safe?

    pch.quizShowAnswer

    B — The inner objects cannot be mutated, so sharing them is unobservable — Sharing only matters when the shared object can change. Immutable values — numbers, strings, tuples — are safe to share.

  4. What is a real drawback of `deepcopy`?

    pch.quizShowAnswer

    B — It follows every reference, so it will try to copy things like open files or connections — It is also much slower. For objects holding resources, define `__deepcopy__` or copy just the fields you need.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading