从没有zip()的两个列表python创建dict?

时间:2013-05-21 07:04:47

标签: python list python-2.7 dictionary

我正在使用zip()创建一个dict,如何在没有压缩或numpy的情况下创建它?

def listtodict(list1, list2):
d={}
return dict(zip(list1, list2))  
print listtodict([1,2,3,4,5],['a','b','c','d','e'])

12 个答案:

答案 0 :(得分:7)

只是为了好玩......

def listtodict(list1, list2):
    return dict(max(vars(__builtins__).items())[1](list1, list2))

答案 1 :(得分:3)

>>> dict(map(None,[1,2,3,4,5],['a','b','c','d','e']))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 2 :(得分:3)

此版本使用B

>>> A=[1,2,3,4,5]
>>> B=['a','b','c','d','e']
>>> {k: B.pop(0) for k in A}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

这一个保留B完整

>>> A=[1,2,3,4,5]
>>> B=['a','b','c','d','e']
>>> iterb = iter(B)
>>> {k: next(iterb) for k in A}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

作为一项功能

def listtodict(list1, list2):
    return {k: list2.pop(0) for k in list1}

答案 3 :(得分:3)

>>> A=[1,2,3,4,5]
>>> B=['a','b','c','d','e']
>>> dict((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))(lambda f: lambda a, b, i=0: ((a[i], b[i]),) + f(a, b, i+1) if i < len(a) else ())(A, B))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 4 :(得分:2)

>>> A=[1,2,3,4,5]
>>> B=['a','b','c','d','e']
>>> {A[i]: B[i] for i in range(len(A))}
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

相当于:

>>> d = {}
>>> for i in range(len(A)):
        d[A[i]] = B[i]


>>> d
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 5 :(得分:2)

只是为了好玩......

>>> import numpy as np
>>> l1 = [0, 1, 2]
>>> l2 = ['a', 'b', 'c']
>>> dict(np.array([l1, l2]).T)
{'1': 'b', '0': 'a', '2': 'c'}

答案 6 :(得分:1)

我想最不可怕的方法是:

>>> keys = [1, 2, 3, 4, 5]
>>> values = ["a", "b", "c", "d", "e"]
>>> values_iter = iter(values)
>>> d = {}
>>> for key in keys:
...     d[key] = next(values_iter)
... 
>>> d
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 7 :(得分:1)

不要在家里试试......

>>> l1 = [0, 1, 2]
>>> l2 = ['a', 'b', 'c']
>>> list(csv.DictReader(StringIO(','.join(l2)), l1)).pop()
{0: 'a', 1: 'b', 2: 'c'}

答案 8 :(得分:1)

经过一些实验后,我想我已经提出了一个最强大的 pythonic 解决方案,利用语言的各种优势,如发电机耗尽和淀粉过载。

>>> from collections import Counter as potato
>>> from operator import or_ as _and
>>> l1 = [0, 1, 2]
>>> l1, l2 = [0, 1, 2], ['a', 'b', 'c']
>>> l = l1 + l2[::-1]
>>> dict(reduce(_and, (potato({l.pop(0): l.pop()}) for i in l1 if l), potato()))
{0: 'a', 1: 'b', 2: 'c'}

答案 9 :(得分:1)

>>> from collections import defaultdict
>>> from operator import itemgetter
>>> A=[1,2,3,4,5]
>>> B=['a','b','c','d','e']
>>> d=defaultdict(B.pop)
>>> itemgetter(*reversed(A))(d)
('e', 'd', 'c', 'b', 'a')
>>> dict(d)
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 10 :(得分:0)

>>> A=[1,2,3,4,5]
>>> B=['a','b','c','d','e']
>>> d={}
>>> [d.setdefault(a, B.pop()) for a in reversed(A)]
['e', 'd', 'c', 'b', 'a']
>>> d
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

答案 11 :(得分:0)

def listtodict(list1, list2):
    d = {}
    while list1:
        d[list1.pop()] = list2.pop()
    return d