Skip to article frontmatterSkip to article content

In this lesson, we’ll learn more advanced dictionary features and the CSV data file format. By the end of this lesson, students will be able to:

  • Loop over the keys, values, and items of a dictionary.
  • Identify the list of dictionaries corresponding to some CSV data.
  • Loop over a list of dictionaries (CSV rows) and access dictionary values (CSV columns).
import doctest

Dictionary functions

Dictionaries, like lists, are also mutable data structures so they have functions to help store and retrieve elements.

  • d.pop(key) removes key from d.
  • d.keys() returns a collection of all the keys in d.
  • d.values() returns a collection of all the values in d.
  • d.items() returns a collection of all (key, value) tuples in d.

There are different ways to loop over a dictionary.

dictionary = {"a": 1, "b": 2, "c": 3}
for key in dictionary:
    print(key, dictionary[key])

None in Python

In an earlier lesson, we wrote a function to count the occurrences of each token in a file as a dict where the keys are words and the values are counts.

{"green": 2, "eggs": 6, "and": 3, "yam": 2}

Suppose we want to debug the following function most_frequent that takes this dictionary as input and returns the word with the highest count. If the input were a list, we could index the zero-th element from the list and loop over the remaining values by slicing the list. But it’s harder to do this with a dictionary.

Python has a special None keyword, like null in Java, that represents a placeholder value.

def most_frequent(counts):
    """
    Returns the token in the given dictionary with the highest count, or None if empty.

    >>> most_frequent({"green": 2, "eggs": 6, "and": 3, "yam": 2})
    'eggs'
    >>> most_frequent({}) # None is not displayed as output

    """
    max_word = None
    for word in counts:
        if counts[word] > counts[max_word]:
            max_word = word
    return max_word


doctest.run_docstring_examples(most_frequent, globals())

Loop unpacking

When we need keys and values, we can loop over and unpack each key-value pair by looping over the dictionary.items().

dictionary = {"a": 1, "b": 2, "c": 3}
for key, value in dictionary.items():
    print(key, value)

Loop unpacking is not only useful for dictionaries, but also for looping over other sequences such as enumerate and zip. enumerate is a built-in function that takes a sequence and returns another sequence of pairs representing the element index and the element value.

with open("poem.txt") as f:
    for i, line in enumerate(f.readlines()):
        print(i, line[:-1])

zip is another built-in function that takes one or more sequences and returns a sequence of tuples consisting of the first element from each given sequence, the second element from each given sequence, etc. If the sequences are not all the same length, zip stops after yielding all elements from the shortest sequence.

arabic_nums = [  1,    2,     3,    4,   5]
alpha_nums  = ["a",  "b",   "c",  "d", "e"]
roman_nums  = ["i", "ii", "iii", "iv", "v"]

for arabic, alpha, roman in zip(arabic_nums, alpha_nums, roman_nums):
    print(arabic, alpha, roman)

Comma-separated values

In data science, we often work with tabular data such as the following table representing the names and hours of some of the TAs.

NameHours
Anna20
Iris15
Abiy10
Gege12

A table has two main components to it:

  • Rows corresponding to each entry, such as each individual TA.
  • Columns corresponding to (required or optional) fields for each entry, such as TA name and TA hours.

A comma-separated values (CSV) file is a particular way of representing a table using only plain text. Here is the corresponding CSV file for the above table. Each row is separated with a newline. Each column is separated with a single comma ,.

Name,Hours
Anna,20
Iris,15
Abiy,10
Gege,12

We’ll learn a couple ways of processing CSV data in this course, first of which is representing the data as a list of dictionaries.

staff = [
    {"Name": "Anna", "Hours": 20},
    {"Name": "Iris", "Hours": 15},
    {"Name": "Abiy", "Hours": 10},
    {"Name": "Gege", "Hours": 12},
]
staff

To see the total number of TA hours available, we can loop over the list of dictionaries and sum the “Hours” value.

total_hours = 0
for ta in staff:
    total_hours += ta["Hours"]
total_hours

What are some different ways to get the value of Iris’s hours?

for ta in staff:
    if ta["Name"] == "Iris":
        print(ta["Hours"])

Practice: Largest earthquake place

Suppose we have a dataset of earthquakes around the world stored in the CSV file earthquakes.csv.

idyearmonthdaylatitudelongitudenamemagnitude
nc72666881201672737.672-121.619California1.43
us20006i0y201672721.51594.572Burma4.9
nc72666891201672737.577-118.859California0.06
nc72666896201672737.596-118.995California0.4
nn00553447201672739.378-119.845Nevada0.3

Write a function largest_earthquake_place that takes the earthquake data represented as a list of dictionaries and returns the name of the location that experienced the largest earthquake. If there are no rows in the dataset (no data at all), return None.

For example, considering only the data shown above, the result would be "Burma" because it had the earthquake with the largest magnitude (4.9).

def largest_earthquake_place(path):
    """
    Returns the name of the place with the largest-magnitude earthquake in the specified CSV file.

    >>> largest_earthquake_place("earthquakes.csv")
    'Northern Mariana Islands'
    """
    import pandas as pd
    earthquakes = pd.read_csv(path).to_dict("records")
    ...


doctest.run_docstring_examples(largest_earthquake_place, globals())