How can I make a dictionary (dict) from separate lists of keys and values?
You can use the zip function to create a dictionary from separate lists of keys and values like this:
You can use the zip function to create a dictionary from separate lists of keys and values like this:
Using the zip function to create a dictionary from separate lists of keys and values in Python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can also use the dict constructor and pass it a list of tuples, where each tuple consists of a key-value pair:
Using the dict constructor and pass it a list of tuples in Python
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict([(keys[i], values[i]) for i in range(len(keys))])
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}