Lesson 2 of 10

Dict comprehensions

Goal

Filter and invert a dict in one line

01

Explanation

What you learned with lists works for dicts too. You write {k: v for k, v in d.items()} with curly braces and a colon between the key and the value, and .items() hands you the key and the value together on each pass.

With this shape you can filter a dict by adding a condition at the end, or invert it so the values become keys and the keys become values: {v: k for k, v in d.items()}. A lookup by value then becomes a lookup by key, which is faster and clearer than a loop that searches the whole dict.

Be careful when inverting, though: keys can't repeat. If a value appears more than once in the original dict, only its last key survives and the earlier ones vanish with no error or warning. So only invert a dict whose values are unique.

02

Your task

From prices, build the dict cheap with everything that costs less than 10. Write the function invert(d) so it returns any dict inverted, then write by_city = invert(codes). Use dict comprehensions for all of it.

Checks

5 checks
  1. cheap holds only what costs less than 10
  2. prices is unchanged
  3. invert inverts any dict
  4. by_city gives each city's code
  5. Written with dict comprehensions
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.