Creating a dictionary from two iterables and consuming both of them
-
12-10-2019 - |
Question
Suppose I have two lists and I want to make a dictionary from them. Like:
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}
This works as I'd want it to and since the lists are not of equal length, the elements 4
and 5
are left out and there is no corresponding value for them. That is as expected.
But what if I want a value, say None
for the keys in l
? I'd want the output to be:
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
One of the solutions I thought was to iterate over both, compare their lengths and append None
where required. I have a solution that works also, but I was wondering whether it can be done in a much easier and shorter way perhaps?
Solution
Use
dict(itertools.izip_longest(l, x))
# {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow