Converting two lists into a dictionary is a breeze in Python when using the dict
and zip
methods! Additionally, there are alternatives.
Using Zip & Dict
1
2
3
4
| >>> students = ["Cody", "Ashley", "Kerry"]
>>> grades = [93.5, 95.4, 82.8]
>>> dict(zip(students, grades))
{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}
|
Dictionary Comprehension
1
2
3
4
| >>> students = ["Cody", "Ashley", "Kerry"]
>>> grades = [93.5, 95.4, 82.8]
>>> {s: g for s, g in zip(students, grades)}
{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}
|
Python <= 2.6
1
2
3
4
5
| >>> from itertools import izip
>>> students = ["Cody", "Ashley", "Kerry"]
>>> grades = [93.5, 95.4, 82.8]
>>> dict(izip(keys, values))
{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}
|