Exercise: Dictionaries

These exercises combine many of the skills and data types you've learned over the last few units, so you may find yourself consulting previous articles or exercises. For example, the first exercise can be solved nicely with f strings and string methods.

Movie summarizer

def movie_summary(movie): """ Accepts movie, a dictionary with three keys- title (string), duration (number), actors (list of strings), and returns a string of the form "<title> lasts for <duration> minutes. Stars: <actor, ...>" >>> puff = { ... "title": "Puff the Magic Dragon", ... "duration": 30, ... "actors": ["Puff", "Jackie", "Living Sneezes"] ... } >>> movie_summary(puff) 'Puff the Magic Dragon lasts for 30 minutes. Stars: Puff, Jackie, Living Sneezes.' >>> arrival = { ... "title": "Arrival", ... "duration": "118", ... "actors": ["Amy Adams", "Jeremy Renner"] ... } >>> movie_summary(arrival) 'Arrival lasts for 118 minutes. Stars: Amy Adams, Jeremy Renner.' """ return "" # REPLACE THIS LINE

Lists of dicts

The next exercises deals with a list of dicts, like:

coords = [
   {"x": 1, "y": 2},
   {"x": 5, "y": 8}
]

You've dealt with lists before and you've dealt with dicts before, so you can follow the same rules as long as you remember what sort of data type you're retrieving data from. For example, in a list of dicts, you'd use bracket notation with an index to access the first dict, and then use bracket notation with a key to access values inside the dict.

Exercise: Book list

This list stores information about books inside nested dicts:

books = [
  {"title": "Uncanny Valley",
  "author": "Anna Wiener",
  "read": False
  },
  {"title": "Parable of the Sower",
  "author": "Octavia E. Butler",
  "read": True
  }
]

🧠 Check Your Understanding

What expression would access the title of the first book?

🧠 Check Your Understanding

What expression would report how many keys are in the second book dict?

Now implement count_unread_books, a function that processes a list of that form and returns the number of unread books in the list.

def count_unread_books(books): """ Accepts a list of dicts describing books and returns the number of unread books in the list. >>> books = [{ ... "title": "Uncanny Valley", ... "author": "Anna Wiener", ... "read": False ... }, { ... "title": "Parable of the Sower", ... "author": "Octavia E. Butler", ... "read": True ... }] >>> count_unread_books(books) 1 """ # Initialize a count to 0 # Iterate through the books # If a book is not read, increment count # Return count
➑️ Next up: Randomness