Ever had two lists — one with keys and one with values — and wondered how to merge them into a dictionary?
Method 1: Comprehension loop
Let’s say you have:
people = [
"Alice", "Bob", "Charlie", "Diana", "Ethan",
"Fiona", "George", "Hannah", "Isaac", "Julia",
"Kevin", "Laura", "Michael", "Nina", "Oscar"
]
heights = [
165, 178, 172, 160, 185,
170, 182, 158, 174, 169,
180, 162, 176, 168, 181
]
Now turning the two lists into a dictionary using comprehension loops:
people_heights = {people[i]: heights[i] for i in range(len(people))}
people_heights
outcome:
{'Alice': 165,
'Bob': 178,
'Charlie': 172,
'Diana': 160,
'Ethan': 185,
'Fiona': 170,
'George': 182,
'Hannah': 158,
'Isaac': 174,
'Julia': 169,
'Kevin': 180,
'Laura': 162,
'Michael': 176,
'Nina': 168,
'Oscar': 181}
Method 2: Using zip
Let's say you have:
pumpkin = ["a","b","c","d","e","f"]
weights = [19,14,15,9,10,17]
Now combining the lists into a dictionary:
pumpkin_dict = dict(zip(pumpkin,weights))
pumpkin_dict
Outcome:
{'a': 19, 'b': 14, 'c': 15, 'd': 9, 'e': 10, 'f': 17}
Top comments (0)