Learn to Combine Two Lists into a Dictionary: 5 Easy Examples
Here are five examples of creating a dictionary from two lists:
- Example 1: Zip Function
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary)
Output:
{'a': 1, 'b': 2, 'c': 3}
- Example 2: Using a Loop
keys = ['x', 'y', 'z']
values = [10, 20, 30]
dictionary = {}
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
print(dictionary)
Output:
{'x': 10, 'y': 20, 'z': 30}
- Example 3: Using Dictionary Comprehension
keys = ['apple', 'banana', 'cherry']
values = [5, 10, 15]
dictionary = {keys[i]: values[i] for i in range(len(keys))}
print(dictionary)
Output:
{'apple': 5, 'banana': 10, 'cherry': 15}
- Example 4: Using
zip()
with Unpacking
keys = ['one', 'two', 'three']
values = [111, 222, 333]
dictionary = {k: v for k, v in zip(keys, values)}
print(dictionary)
Output:
{'one': 111, 'two': 222, 'three': 333}
- Example 5: Using
dict()
withzip()
and Lists
keys = ['dog', 'cat', 'bird']
values = ['woof', 'meow', 'tweet']
dictionary = dict(zip(keys, values))
print(dictionary)
Output:
{'dog': 'woof', 'cat': 'meow', 'bird': 'tweet'}
These examples demonstrate various ways to create a dictionary from two lists in Python.