使用python中的for循环从两个列表创建字典列表

时间:2019-02-24 06:00:21

标签: python list for-loop

我有两个列表:

providers = ["a", "b", "c", "d", "e"]
ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]

我希望输出看起来像:

[{'provider_name':'a', 'server':'100.12.23.34'},.....]

我该如何在Python中使用for循环?

3 个答案:

答案 0 :(得分:2)

这是一个易于遵循的解决方案。如需更多有关zip方法的信息,请click here

new = []

# e is the index
for i, j in zip(providers, ips):
    new.append({"provider_name": i, "server": j})

答案 1 :(得分:1)

使用:

>>> providers = ["a", "b", "c", "d", "e"]
>>> ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]
>>> [{'provider_name':x, 'server':y} for x,y in zip(providers,ips)]
[{'provider_name': 'a', 'server': '100.12.23.34'}, {'provider_name': 'b', 'server': '199.134.3.01'}, {'provider_name': 'c', 'server': '123.143.2.34'}, {'provider_name': 'd', 'server': '154.234.4.66'}]
>>> 

答案 2 :(得分:0)

不带任何拉链的选项:

providers = ["a", "b", "c", "d", "e"]
ips = ["100.12.23.34", "199.134.3.01", "123.143.2.34", "154.234.4.66"]

[ {'provider_name': providers[i], 'server': ips[i] } for i in range(len(ips)) ]