Dictionaries and Lists Together

Dictionaries and Lists Together

A list of dictionaries represents a table of records — one dictionary per row, one key per column:

people = [
    {"name": "Ada", "age": 36},
    {"name": "Grace", "age": 45},
    {"name": "Alan", "age": 41},
]

Looping over the list gives one dictionary at a time; indexing into it reads a field:

for person in people:
    print(person["name"])

Output:

Ada
Grace
Alan

Values in a dictionary can also be lists:

teams = {"red": ["Ada", "Grace"], "blue": ["Alan"]}
print(len(teams["red"]))

Output:

2

These two shapes — list of dictionaries, dictionary of lists — cover most everyday data.

Exercise

  1. Define a function named adult_names with one parameter, people — a list of dictionaries, each with a "name" and an "age" key.
  2. It returns a list of the names of everyone aged 18 or over, in order.

With the people list above, adult_names(people) returns ["Ada", "Grace", "Alan"].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestAdultNames(unittest.TestCase):
    def test_mixed_ages(self):
        people = [
            {"name": "Ada", "age": 36},
            {"name": "Linus", "age": 12},
            {"name": "Grace", "age": 45},
        ]
        self.assertEqual(adult_names(people), ["Ada", "Grace"])

    def test_exactly_18_counts_as_adult(self):
        self.assertEqual(adult_names([{"name": "Kim", "age": 18}]), ["Kim"])

    def test_empty_list(self):
        self.assertEqual(adult_names([]), [])
def adult_names(people):
    result = []
    for person in people:
        if person["age"] >= 18:
            result.append(person["name"])
    return result


guests = [
    {"name": "Ada", "age": 36},
    {"name": "Linus", "age": 12},
    {"name": "Grace", "age": 45},
]
print(adult_names(guests))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.