Python Nested Dictionaries and JSON
What you will learn
- How to read and change dictionaries nested inside dictionaries and lists
- How to read deep values safely
- Working with a list of records and a dictionary of records
- Building nested data with
setdefault, and flattening it - Converting to and from JSON text, and what JSON cannot hold
1. Nested data
The values of a dictionary can be dictionaries and lists, so dictionaries can describe real-world data of any shape. This is a made-up company:
company = {
"name": "Pathkori Ltd",
"address": {"city": "Dhaka", "country": "BD", "geo": {"lat": 23.8, "lon": 90.4}},
"staff": [
{"name": "Rina", "skills": ["python", "sql"]},
{"name": "Sam", "skills": []},
],
"active": True,
"founded": None,
}
To reach a deep value, chain the lookups: one [ ] for each level, using a key for a dictionary and an index for a list:
print(company["address"]["city"])
print(company["address"]["geo"]["lat"])
print(company["staff"][0]["skills"][1])
print(company["staff"][1]["name"])
Dhaka
23.8
sql
Sam
Read the last line from left to right: the company's staff list, its item 1 (a dictionary), and that dictionary's "name".
Quick check: how would you read Rina's first skill?
company["staff"][0]["skills"][0], which is "python".
2. Missing keys and safe reading
A chain fails at the first missing link:
company["contact"]["email"]
KeyError: 'contact'
company["founded"]["year"]
TypeError: 'NoneType' object is not subscriptable
The second error happens because company["founded"] is None, and you cannot look up a key in None. For optional levels, use get with an empty dictionary as the default, so the next get has something to work on:
print(company.get("contact", {}).get("email"))
print(company.get("contact", {}).get("email", "n/a"))
print(company["address"].get("zip", "none"))
None
n/a
none
When many levels are optional, a small helper function walks the path and gives a default if any step is missing (functions are chapter 11, and *path collects the steps, lesson 11.4):
def deep_get(d, *path, default=None):
for key in path:
if isinstance(d, dict) and key in d:
d = d[key]
else:
return default
return d
print(deep_get(company, "address", "geo", "lat"))
print(deep_get(company, "address", "geo", "alt", default="?"))
print(deep_get(company, "x", "y"))
23.8
?
None
3. Changing nested data
Assign at the end of the chain. New keys appear, old ones change, lists grow:
company["address"]["zip"] = "1207"
company["contact"] = {"email": "info@example.com"}
company["address"]["geo"]["lat"] = 24.0
company["staff"].append({"name": "Lee", "skills": ["go"]})
company["staff"][1]["skills"].append("excel")
print(company["address"])
print(company["contact"], len(company["staff"]))
print(company["staff"][1])
{'city': 'Dhaka', 'country': 'BD', 'geo': {'lat': 24.0, 'lon': 90.4}, 'zip': '1207'}
{'email': 'info@example.com'} 3
{'name': 'Sam', 'skills': ['excel']}
You can only assign inside a level that exists: company["a"]["b"] = 1 fails if "a" is missing. setdefault creates the levels as you go:
config = {}
config.setdefault("db", {}).setdefault("host", "localhost")
config["db"]["port"] = 5432
print(config)
{'db': {'host': 'localhost', 'port': 5432}}
(collections.defaultdict does this more neatly, lesson 9.6.)
4. Looping through nested data
Loop one level at a time, as in lesson 9.3:
for person in company["staff"]:
print(person["name"], len(person["skills"]), end="; ")
print()
for key, value in company["address"].items():
print(key, "->", value, end="; ")
print()
Rina 2; Sam 1; Lee 1;
city -> Dhaka; country -> BD; geo -> {'lat': 24.0, 'lon': 90.4}; zip -> 1207;
Comprehensions work for queries on the records:
print([p["name"] for p in company["staff"] if "python" in p["skills"]])
print({p["name"]: len(p["skills"]) for p in company["staff"]})
print(sorted({s for p in company["staff"] for s in p["skills"]}))
['Rina']
{'Rina': 2, 'Sam': 1, 'Lee': 1}
['excel', 'go', 'python', 'sql']
The last line collects every skill into a set (no repeats) and sorts it. The for parts read like nested loops (lesson 7.5).
5. Two ways to store records
| Shape | Example | Best when |
|---|---|---|
| list of dictionaries | [{"name": "Rina", "age": 25}, ...] |
the order matters, or you mostly loop over everyone |
| dictionary of dictionaries | {101: {"name": "Rina", "age": 25}, ...} |
you look records up by an id |
users = {101: {"name": "Rina", "age": 25}, 102: {"name": "Sam", "age": 22}}
print(users[101]["name"])
print(max(users.values(), key=lambda u: u["age"])["name"])
print({uid: u["name"] for uid, u in users.items()})
Rina
Rina
{101: 'Rina', 102: 'Sam'}
A lookup by id in a dictionary is fast, while finding a record in a list means scanning it (lesson 7.7).
A tuple can also be a key, so {("r1", "c2"): 6} is a simple table, read as table["r1", "c2"]. Nested dictionaries matrix["r1"]["c2"] do the same, and let you ask for a whole row.
6. Flattening
To turn nested keys into one level with dotted names, use a function that calls itself (recursion, lesson 11.6):
def flatten(d, prefix=""):
out = {}
for k, v in d.items():
key = f"{prefix}{k}"
if isinstance(v, dict):
out.update(flatten(v, key + "."))
else:
out[key] = v
return out
print(flatten({"a": 1, "b": {"c": 2, "d": {"e": 3}}}))
{'a': 1, 'b.c': 2, 'b.d.e': 3}
This is handy for settings and for writing nested data into a flat table.
7. JSON: nested data as text
JSON (JavaScript Object Notation) is a text format for nested data, used by websites, settings files and APIs. It looks almost the same as a Python dictionary. The json module converts between the two (files are chapter 15):
| Function | Direction |
|---|---|
json.dumps(data) |
Python data to a JSON string |
json.loads(text) |
a JSON string back to Python data |
import json
text = json.dumps({"a": 1, "b": [True, None, 2.5], "c": "é"})
print(text)
print(json.loads(text))
{"a": 1, "b": [true, null, 2.5], "c": "\u00e9"}
{'a': 1, 'b': [True, None, 2.5], 'c': 'é'}
JSON writes true, false and null where Python writes True, False and None, and dumps writes non-English letters as escapes by default. Useful options:
print(json.dumps({"c": "é"}, ensure_ascii=False))
print(json.dumps({"b": 2, "a": {"x": 1}}, indent=2, sort_keys=True))
{"c": "é"}
{
"a": {
"x": 1
},
"b": 2
}
indent=2makes the text readable.sort_keys=Trueorders the keys.ensure_ascii=Falsekeeps accented letters as they are.
The type table
| Python | JSON |
|---|---|
dict |
object {...} |
list, tuple |
array [...] |
str |
string |
int, float |
number |
True, False |
true, false |
None |
null |
What JSON cannot hold
- Dictionary keys are always text. Other keys are turned into text, so they come back different:
print(json.dumps({1: "int key", True: "bool", None: "none"}))
print(json.loads(json.dumps({1: "x"})))
{"1": "bool", "null": "none"}
{'1': 'x'}
(1 and True were the same key, lesson 9.1, so one pair was lost.) The key 1 came back as '1'.
- Tuples become lists, and sets, custom objects and tuple keys are errors:
json.dumps({"s": {1, 2}})
TypeError: Object of type set is not JSON serializable
json.dumps({(1, 2): "t"})
TypeError: keys must be str, int, float, bool or None, not tuple
- Invalid JSON raises
json.JSONDecodeError. JSON needs double quotes:json.loads("{'a': 1}")fails withExpecting property name enclosed in double quotes.
8. Copying nested data
A copy of a nested dictionary shares the inner dictionaries unless you copy deeply (lessons 7.5 and 9.5):
import copy
a = {"k": {"n": [1]}}
shallow = a.copy()
shallow["k"]["n"].append(2)
deep = copy.deepcopy(a)
deep["k"]["n"].append(3)
print(a)
print(deep)
{'k': {'n': [1, 2]}}
{'k': {'n': [1, 2, 3]}}
The shallow copy shared the inner data, so a changed. The deep copy was independent. A neat trick is that json.loads(json.dumps(data)) also makes a deep copy of plain data, but copy.deepcopy is clearer and works on more types.
Worked example: answering questions about team data
team = {
"Rina": {"age": 25, "skills": ["python", "sql"]},
"Sam": {"age": 22, "skills": ["excel"]},
"Lee": {"age": 31, "skills": ["python", "go", "sql"]},
}
pythonistas = [n for n, p in team.items() if "python" in p["skills"]]
most_skills = max(team, key=lambda n: len(team[n]["skills"]))
by_skill = {}
for name, p in team.items():
for skill in p["skills"]:
by_skill.setdefault(skill, []).append(name)
print(pythonistas)
print(most_skills)
print(by_skill)
print(sum(p["age"] for p in team.values()) / len(team))
['Rina', 'Lee']
Lee
{'python': ['Rina', 'Lee'], 'sql': ['Rina', 'Lee'], 'excel': ['Sam'], 'go': ['Lee']}
26.0
| Question | Tool |
|---|---|
| who knows Python? | a list comprehension with a condition |
| who has the most skills? | max(..., key=...) |
| who knows each skill? | a nested loop with setdefault(...).append(...) |
| average age | sum(...) / len(...) over the inner values |
The people, ages and skills are made up.
Common mistakes
- Chaining
[]through a level that may be missing, which gives aKeyError. Useget(key, {}). - Looking inside
None, which gives aTypeError. - Copying nested data with
.copy()and changing the inner parts. - Expecting JSON to keep non-text keys, tuples or sets.
- Using single quotes in JSON text. JSON requires double quotes.
Key takeaways
- Nested data is read with chained lookups: a key for a dictionary, an index for a list.
- Use
get(key, {})or a helper to read optional levels safely;setdefaultbuilds levels as you go. - Store records as a list of dictionaries, or as a dictionary of dictionaries when you look them up by id.
json.dumpsturns data into text andjson.loadsback;indent,sort_keysandensure_asciicontrol the text.- JSON keys become text, tuples become lists, and sets cannot be written; use
copy.deepcopyfor independent copies.
Practice
1. With d = {"a": {"b": {"c": 7}}}, how do you read 7?
Show answer
d["a"]["b"]["c"].
2. Read d["x"]["y"] safely, giving 0 if any level is missing.
Show answer
d.get("x", {}).get("y", 0).
3. Convert {"name": "Rina", "age": 25} to JSON text and back.
Show answer
import json
text = json.dumps({"name": "Rina", "age": 25})
data = json.loads(text)
4. What happens to the key 5 in json.loads(json.dumps({5: "x"}))?
Show answer
It comes back as the text "5", because JSON object keys are always text.
5. Why does json.dumps({"s": {1, 2}}) fail, and how can you fix it?
Show answer
A set is not a JSON type. Convert it to a list first: json.dumps({"s": sorted({1, 2})}).
6. From users = {101: {"name": "Rina"}, 102: {"name": "Sam"}}, make {101: "Rina", 102: "Sam"}.
Show answer
{uid: u["name"] for uid, u in users.items()}.