将值设置为无将两个列表压缩到字典中

时间:2014-02-27 20:36:58

标签: python dictionary

如果值列表超出范围,我怎样才能将值设置为无拉链两个列表,例如:

a = [1,2,3,4,5]
b = ['a','b','c']
dict(zip(a,b))

因此输出结果为{1:'a', 2:'b', 3:'c'},但我需要{1:'a', 2:'b', 3:'c', 4:None, 5:None}

2 个答案:

答案 0 :(得分:6)

itertools模块可以帮助您。

http://docs.python.org/2/library/itertools.html#itertools.izip_longest

  

itertools.izip_longest(* iterables [,fillvalue])

     

创建一个聚合来自每个迭代的元素的迭代器。   如果迭代的长度不均匀,则填充缺失值   有fillvalue。迭代继续,直到最长的可迭代为止   累。

答案 1 :(得分:2)

这个怎么样:

b = ['a','b','c'] + [None]*(len(a)-len(b))

或者在构造dict时这样做:

dict(zip(a,b +[None]*(len(a)-len(b))))