Depending on the relative list lengths you will want to use either zip
or zip_longest
.
Example:
from itertools import zip_longest
keys = ['a','b','c']
values = [1,2, 3, 4, 5]
zip_best = zip if len(values) > len(keys) else zip_longest
c = dict(zip_best(keys, values))
print(c)
Output:
{'a': 1, 'b': 2, 'c': 3}
Edit #1: In response to OP's comment, there are many ways to build lists from user input, but here is one simple way you could construct keys
and values
lists from user input if you weren't concerned about error handling:
Example:
keys = input("Enter space separated single letter keys: ").split()
values = list(map(int, input("Enter space separated integer values: ").split()))
Edit #2: In response to OP's most recent comment below, zip_longest
provides None
padding, so in case it wasn't clear, my proposed solution also handles the case where there are more keys than values.
Example:
from itertools import zip_longest
keys = ['a','b','c']
values = [1,2]
zip_best = zip if len(values) > len(keys) else zip_longest
c = dict(zip_best(keys, values))
print(c)
Output:
{'a': 1, 'b': 2, 'c': None}