Dictionary Comprehensions
You can build a dictionary in one line too. In the lesson on dictionaries, you filled an empty dictionary in a loop, one key at a time:
names = ["Anna", "Tom", "Eva"]
lengths = {}
for name in names:
lengths[name] = len(name)
print(lengths){'Anna': 4, 'Tom': 3, 'Eva': 3}A dictionary comprehension does the same in one line. It's written in curly braces, and its first part is a pair: a key, a colon and a value, just like a pair in a dictionary you write out:
names = ["Anna", "Tom", "Eva"]
lengths = {name: len(name) for name in names}
print(lengths){'Anna': 4, 'Tom': 3, 'Eva': 3}For each name, the new dictionary gets a pair: the name as the key and its length as the value.
Often you make a new dictionary from another one. The for part then goes through .items() with two variables, as a loop does, and an if at the end picks the pairs. This keeps the things on a menu that cost less than 50:
menu = {"coffee": 45, "tea": 35, "cake": 60, "juice": 50}
cheap = {item: price for item, price in menu.items() if price < 50}
print(cheap){'coffee': 45, 'tea': 35}Without .items(), the comprehension gets only the keys, and just like the loop, it ends with ValueError: too many values to unpack (expected 2).
And curly braces without a colon? That's a set comprehension, and it gives you a set: each value is in it only once. That's handy for collecting the different values of a list, here the places a class voted for, written in different ways:
votes = ["Zoo", "castle", "zoo", "Castle", "aquapark", "zoo"]
places = {vote.lower() for vote in votes}
print(len(places))
print(sorted(places))3
['aquapark', 'castle', 'zoo']Remember that a set has no order: printed, a set of texts can come out in a different order every time you run the program. That's why this one is printed sorted.
Instructions
- 1
The teacher wants the results in percent. 50 points are 100%, so the percentage is the points times 2. Make a dictionary
percentwith a dictionary comprehension overpoints.items(): the same names, each with its points times 2. Print it:{'Anna': 84, 'Tom': 56, 'Eva': 94, 'Max': 70, 'Lily': 38}. Keep the line withpointsas it is: the exercise also checks your program with other results. - 2
You pass the test with at least 30 points. Below, make a dictionary
passedwith a second dictionary comprehension: only the students frompointswho passed, with their points. Print it:{'Anna': 42, 'Eva': 47, 'Max': 35}.