Convert two lists into a dictionary in Python
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>>> students = ["Cody", "Ashley", "Kerry"]
2>>> grades = [93.5, 95.4, 82.8]
3>>> dict(zip(students, grades))
4{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}
Dictionary Comprehension
1>>> students = ["Cody", "Ashley", "Kerry"]
2>>> grades = [93.5, 95.4, 82.8]
3>>> {s: g for s, g in zip(students, grades)}
4{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}
Python <= 2.6
1>>> from itertools import izip
2>>> students = ["Cody", "Ashley", "Kerry"]
3>>> grades = [93.5, 95.4, 82.8]
4>>> dict(izip(keys, values))
5{'Cody': 93.5, 'Ashley': 95.4, 'Kerry': 82.8}