Lesson 9
No Object is an Island
Chapter 5: List comprehension
Dict comprehension exercise
Here is one more exercise - for dictionary comprehension.
ids
below is a dict
with the person’s name as the key and their id as the value.
You should use dictionary comprehension to produce another dictionary where the person’s id is the key and the person’s name is the value. You should also limit the dictionary to only contain people whose id starts with 2
.
ids = {"Luca": "20013", "Josiah": "10027", "Rob": "10112", "Harry": "20064"}
names = ????
assert names == {'20013': 'Luca', '20064': 'Harry'}
No peeking at the solutions until you have tried it! 👀
A possible solution:
ids = {"Luca": "20013", "Josiah": "10027", "Rob": "10112", "Harry": "20064"}
names = {ident: name for (name, ident) in ids.items() if ident.startswith("2")}