Comprehensions

INPUT · Slides

Dictionaries in one line too

01 / 06

Change the punctuation round it

So far you have used square brackets [ ], which is why you kept getting lists.

Change them for braces { } and put key: value at the front, and what you get is a dictionary.

names = ["Yui", "Haruto"]print({n: len(n) for n in names})

Result

{'Yui': 3, 'Haruto': 6}

02 / 06

The two shapes side by side

There are only two differences: the punctuation round it and whether there is a colon at the front.

  • a list … [ value for a name in what you loop over ]
  • a dictionary … { key: value for a name in what you loop over }

The for part behind is identical, and you can add an if to either. The skeleton is shared; the punctuation decides the container.

names = ["Yui", "Haruto"]print([len(n) for n in names])print({n: len(n) for n in names})

Result

[3, 6]
{'Yui': 3, 'Haruto': 6}

03 / 06

The order is kept

A dictionary remembers the order things went in, as you saw in Chapter 2.

So the result of a dictionary comprehension comes out in the order you looped. You can show it as it is without worrying.

print({x: x * x for x in range(1, 5)})

Result

{1: 1, 2: 4, 3: 9, 4: 16}

04 / 06

Build a dictionary from a dictionary with items()

When the thing you are looping over is a dictionary, the set move is to bring in items() — the one that hands you a key and a value at a time.

Write for k, v in prices.items() and k holds the key, v the value. After that, build whatever you like at the front.

prices = {"apple": 100, "orange": 80}print({k: v * 2 for k, v in prices.items()})

Result

{'apple': 200, 'orange': 160}

05 / 06

Swap the keys and the values

With items() you can also build a dictionary with the keys and values the other way round, in one line. You only write v: k at the front.

It turns a "look a value up by name" table into a "look a name up by value" one. Written with for it runs to a fair few lines, so it shows off plainly what a comprehension buys you.

colours = {"apple": "red", "grape": "purple"}print({v: k for k, v in colours.items()})

Result

{'red': 'apple', 'purple': 'grape'}

06 / 06

You can add an if

An if at the back works just as it does for a list. You get a dictionary holding only the pairs that match.

"Make a register of the ones who passed" comes down to one line. Next lesson we keep the braces and take the colon away.

scores = {"Yui": 80, "Haruto": 45, "Minato": 60}print({k: v for k, v in scores.items() if v >= 60})

Result

{'Yui': 80, 'Minato': 60}