Reputation: 445
My task: I have 2 lists different size(1,2,3,4 and "qwe","asd","zxc" for example). How I can create dictionary with this lists with next condition: if count of keys more than values- dict[key]=None. If count of values more-just inore it. My code:
list1=[1,2,3,4]
list2=["qwe","asd","zxc"]
dictx={}
for x in range(len(list1)):
if x>len(list2):
dictx[list1[x]]=None
else:
dictx[list1[x]]=list2[x]
But I catch error: Traceback (most recent call last): File "", line 5, in dictx[list1[x]]=list2[x] IndexError: list index out of range Where I do mistake?Python 3.4 Upd.It's work, but I try to understand where my mistake in this code. Anybody have thought?
Upvotes: 0
Views: 1609
Reputation: 4318
You can also use itertools.izip_longest as follows:
import itertools
list1=[1,2,3,4]
list2=["qwe","asd","zxc"]
print ({l1:l2 for l1,l2 in itertools.izip_longest(list1,list2,fillvalue=None)})
EDIT: In python 3:
import itertools
list1=[1,2,3,4]
list2=["qwe","asd","zxc"]
print ({l1:l2 for l1,l2 in itertools.zip_longest(list1,list2,fillvalue=None)})
Output:
{1: 'qwe', 2: 'asd', 3: 'zxc', 4: None}
Upvotes: 3
Reputation: 280837
Pad the value list with None
s using itertools.chain
and itertools.repeat
, then zip the lists:
from itertools import chain, repeat
d = dict(zip(list1, chain(list2, repeat(None))))
repeat(None)
is an infinite iterator that yields None
forever.
chain(list2, repeat(None))
is an iterator that yields items from list2
, then yields None
s when list2
runs out.
zip(...)
returns a list of pairs of corresponding elements from list1
and the padded list2
. zip
stops when any input runs out, so the input is as long as list1
.
Finally, dict(...)
takes the list of key-value pairs and makes a dict with those keys corresponding to those values.
Upvotes: 3