Summary

In this lesson, you learned that:

  • A dictionary keeps together values that describe one thing: {"name": "Anna", "age": 21}. It is made of key–value pairs, separated by commas, with a colon between the key and the value.
  • print() shows a dictionary with text in single quotes: {'name': 'Anna', 'age': 21}. The pairs stay in the order in which they were added.
  • You read a value with its key in square brackets: person["name"]. A key that isn't there ends the program with a KeyError. Uppercase and lowercase letters in keys matter. In an f-string, write the key in single quotes: f"{person['name']}".
  • Assigning changes a value (person["age"] = 22) or adds a new pair (person["city"] = "Brno"). Each key is in a dictionary only once. {} is an empty dictionary, and len() gives the number of pairs.
  • "phone" in person checks whether a key is there. person.get("phone", "unknown") reads a value without an error: when the key is missing, it gives the default value (without one, None).
  • The key in square brackets can be in a variable: menu[item].
  • for key in person: goes through the keys, and for key, value in person.items(): goes through the keys and values together.
  • A dictionary is great for counting: counts[x] = counts.get(x, 0) + 1.
  • A list of dictionaries holds many things of the same kind. movies[1]["title"] is the title of the second movie, and a for loop goes through the list one dictionary at a time.
  • A function can take a dictionary or a list of dictionaries as an argument, and it can return a new dictionary.

In the next lesson, the final project, you'll put together everything you've learned in this course (variables, conditions, lists, loops, functions and dictionaries) and build a whole program step by step.

Now some practice. The fruit shop in the editor keeps its stock in a dictionary: each fruit and how many pieces of it are left.

Instructions

Write a function sold_out(counts) that returns a list of the fruits whose count in the dictionary counts is 0. Call it with stock and print the result: ['lemons', 'plums'].

The shop has received 20 lemons, and it has started to sell kiwis too, but none have arrived yet. Below, set the count of "lemons" to 20, add the key "kiwis" with the value 0 and print sold_out(stock) again: ['plums', 'kiwis'].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/9