Learn
Creating Dictionaries
List Comprehensions to Dictionaries
Let’s say we have two lists that we want to combine into a dictionary, like a list of students and a list of their heights, in inches:
names = ['Jenny', 'Alexus', 'Sam', 'Grace'] heights = [61, 70, 67, 64]
Python allows you to create a dictionary using a list comprehension, with this syntax:
students = {key:value for key, value in zip(names, heights)} #students is now {'Jenny': 61, 'Alexus': 70, 'Sam': 67, 'Grace': 64}
Remember that zip()
combines two lists into a zipped list of pairs. This list comprehension:
- Takes a pair from the zipped list of pairs from
names
andheights
- Names the elements in the pair
key
(the one originally from thenames
list) andvalue
(the one originally from theheights
list) - Creates a
key
:value
item in thestudents
dictionary - Repeats steps 1-3 for the entire list of pairs
Instructions
1.
You have two lists, representing some drinks sold at a coffee shop and the milligrams of caffeine in each. First, create a variable called zipped_drinks
that is a zipped list of pairs between the drinks
list and the caffeine
list.
2.
Create a dictionary called drinks_to_caffeine
by using a list comprehension that goes through the zipped_drinks
list and turns each pair into a key:value item.