Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从两个列表创建词典?_Python_List_Dictionary - Fatal编程技术网

Python 如何从两个列表创建词典?

Python 如何从两个列表创建词典?,python,list,dictionary,Python,List,Dictionary,我有两个不同的列表,我需要它们像这样显示。我觉得我很接近了,但是程序不起作用。另外,一个带有zip的版本在这里也不适合我 >>> list_to_dict(["a", "b"], ["13", "7" ]) { "a": "13", "b": "7" } 这就是我现在拥有的: def lists_to_dict(): x = ['a', 'b'] y = ['13', '7'] d = {} for i in range(len(x)):

我有两个不同的列表,我需要它们像这样显示。我觉得我很接近了,但是程序不起作用。另外,一个带有
zip
的版本在这里也不适合我

>>> list_to_dict(["a", "b"], ["13", "7" ])
{ "a": "13", "b": "7" }
这就是我现在拥有的:

def lists_to_dict():
    x = ['a', 'b']
    y = ['13', '7']
    d = {}
    for i in range(len(x)):
        d[x[i]] = y[i]
    return d

lists_to_dict()

dict(zip(x,y))
应该是您所需要的全部。

同样的无拉链解决方案,作为一种理解被重新打包:

>>> a = ["a", "b"]
>>> b = ["13", "7" ]
>>> print dict(zip(a,b)) 
{'a': '13', 'b': '7'}
>>> 
def lists_to_dict(k, v):
    return { k[i]: v[i] for i in range(min(len(k), len(v))) }

>>> lists_to_dict(['a', 'b'], [13, 7])
{'a': 13, 'b': 7}

为什么zip不能工作?这个代码可以工作。如果您制作
x
y
参数而不是硬编码它们,然后像上面所做的那样传递它们,它也会起作用。怎么了?硬编码参数帮助解决了我遇到的问题。谢谢,我想你的意思是写(zip(x,y))。请添加一些解释!