Skip to content

Prerequisites

Binder

To get maximum benefit from this book, you should know how to program in Python. (Hint: it's an extremely useful skill to know!) In particular, knowing how to:

  1. use dictionaries,
  2. write list comprehensions, and
  3. handle pandas DataFrames,

will help you a ton during the tutorial.

Exercises

We have a few exercises below that should help you get warmed up.

Exercise 1

Given the following line of code:

[s for s in my_fav_things if s[name] == raindrops on roses]

What are plausible data structures for s and my_fav_things?

Exercise 2

Given the following data:

names = [
    {
        'name': 'Eric',
         'surname': 'Ma'
    },
    {
        'name': 'Jeffrey',
        'surname': 'Elmer'
    },
    {
        'name': 'Mike',
        'surname': 'Lee'
    },
    {
        'name': 'Jennifer',
        'surname': 'Elmer'
    }
]

Write a function that takes in the names list of dictionaries and returns the dictionaries in which the surname value matches exactly some query_surname.

def find_persons_with_surname(persons, query_surname):
    # Assert that the persons parameter is a list. 
    # This is a good defensive programming practice.
    assert isinstance(persons, list)   

    results = []
    for ______ in ______:
        if ___________ == __________:
            results.append(________)

    return results

To test your implementation, check it with the following code. No errors should be raised.

# Test your result below.
# results = find_persons_with_surname(names, 'Lee')
# assert len(results) == 1

# results = find_persons_with_surname(names, 'Elmer')
# assert len(results) == 2