keys = ['a', 'b', 'c'] values = [1, 2, 3] my_dict = dict(zip(keys, values)) print(my_dict)
{'a': 1, 'b': 2, 'c': 3}
You can use the zip function to convert two lists into a dictionary. The zip function in Python is used to combine two or more iterables (e.g. lists, tuples, etc.) into a single iterable object.
In this case, we're using zip to combine two lists keys and values into a single iterable. The zip function takes each element of the first iterable, and each corresponding element of the second iterable, and creates a tuple out of them. So, in our example, the first tuple would be ('a', 1).
Finally, we pass the result of the zip function to the dict constructor, which creates a dictionary using the tuples as keys and values. So, in the end, we get a dictionary with the keys 'a', 'b', and 'c' and the values 1, 2, and 3, respectively.
Practice what you just learned
Solve Python exercises and get instant AI feedback on your solutions.
Try ActiveSkill for Free →
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.
