[英]How to create a dictionary from two lists?
I have two different lists, and I need them to be displayed like this. 我有两个不同的列表,我需要这样显示它们。 I feel like I'm close but the program doesn't work. 我觉得我已经接近了,但是该程序无法正常工作。 Also, a version with zip
wouldn't work for me here. 另外,带zip
的版本在这里对我不起作用。
>>> list_to_dict(["a", "b"], ["13", "7" ])
{ "a": "13", "b": "7" }
That's what I have now: 那就是我现在所拥有的:
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))
应该就是您所需要的。
Same zip-less solution that's being tossed about repackaged as a comprehension: 将相同的无拉链解决方案作为一种理解而重新包装:
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}
>>> a = ["a", "b"]
>>> b = ["13", "7" ]
>>> print dict(zip(a,b))
{'a': '13', 'b': '7'}
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.