Lesson 53 +10 XP

Copy and Nested Dictionaries

Copying dictionaries has the same pitfall as lists, and dictionaries can hold anything, even other dictionaries.

Copy with copy()


python
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
mydict = thisdict.copy()

Copy with dict()


python
mydict = dict(thisdict)

Why you can't just assign

mydict = thisdict makes both names point to the SAME dictionary. Changing one changes the other.

Nested dictionaries

A value can itself be a dictionary:


python
myfamily = {
    "child1": {"name": "Emil", "year": 2004},
    "child2": {"name": "Tobias", "year": 2007},
    "child3": {"name": "Linus", "year": 2011}
}

Access nested items

Chain the keys:


python
print(myfamily["child2"]["name"])

### Tobias

Loop through nested dicts


python
for x, obj in myfamily.items():
    print(x)
    for y in obj:
        print(y + ":", obj[y])

TL;DR

  • copy() or dict() make a real copy.
  • Plain assignment shares the same dictionary.
  • Values can be whole dictionaries.
  • Access nested values by chaining keys.