To create a dictionary from two separate lists of keys and values in Python, you can use the built-in zip()
function combined with the dict()
constructor. Here’s a step-by-step guide:
Method 1: Using zip()
and dict()
keys = ["a", "b", "c"]
values = [1, 2, 3]
# Combine the lists into key-value pairs
my_dict = dict(zip(keys, values))
print(my_dict)
# Output: {'a': 1, 'b': 2, 'c': 3}
Method 2: Using a Dictionary Comprehension
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Handling Edge Cases
- Unequal List Lengths:
zip()
truncates to the shortest list. To avoid missing data, ensure lists are of equal length:
if len(keys) == len(values):
my_dict = dict(zip(keys, values))
else:
print("Error: Lists are unequal in length.")
- Duplicate Keys:
The last occurrence of a duplicate key will overwrite previous ones:
keys = ["a", "a", "b"]
values = [1, 2, 3]
print(dict(zip(keys, values))) # Output: {'a': 2, 'b': 3}
Alternative: Loop Explicitly
keys = ["x", "y", "z"]
values = [10, 20, 30]
my_dict = {}
for k, v in zip(keys, values):
my_dict[k] = v
print(my_dict) # Output: {'x': 10, 'y': 20, 'z': 30}
Summary
Approach | Use Case |
---|---|
dict(zip(keys, values)) | Most concise and efficient method |
Dictionary Comprehension | Flexibility (e.g., add conditions) |
Explicit Loop | For custom logic during iteration |
Use zip()
+ dict()
for simplicity and readability in most scenarios.