Data Structures · Dictionaries and Sets · lesson 8 of 10
Nested data
about 14 minutes · free · runs in your browser
Step 1 of 2
Lists of dictionaries
Real data is rarely flat. The shape you will meet most often is a list of dictionaries — exactly what an API hands back:
people = [
{"name": "Ada", "age": 36},
{"name": "Alan", "age": 41},
]
people[0]["name"] # "Ada"
Read the subscripts left to right: people[0] is a dictionary, and ["name"] looks
inside it.
Dictionaries nest too:
config = {"server": {"host": "localhost", "port": 8080}}
config["server"]["port"] # 8080
Your turn: write names_over(people, age) returning the names of everyone older
than the given age, in the order they appear.
You start from this, and edit it in the browser:
def names_over(people, age):
# Return the names of everyone older than age.
pass
Step 2 of 2
Grouping
Turning a flat list into a grouped dictionary is a task you will meet again and again:
groups = {}
for item in items:
key = item["category"]
if key not in groups:
groups[key] = []
groups[key].append(item["name"])
.setdefault(key, []) collapses the middle three lines into one — it returns the
existing list, or inserts and returns a new one.
Your turn: write group_by_city(people) returning a dictionary mapping each city to
the list of names living there, in the order they appear.
You start from this, and edit it in the browser:
def group_by_city(people):
# Return {city: [names]}
pass