从3个列表创建一个字典,其中一个是嵌套列表

时间:2018-11-29 13:38:52

标签: python-3.x

我正在尝试从3个列表中创建一个字典,其中一个是嵌套列表。

Companies = ['Company A', 'Company B']
features = ['Feature 1', 'Feature 2', 'Feature 3']
values = [['On', 'Off', 'On'], ['Off', 'On', 'Off']]

# This is what i would like the out put to look like, any help would be great 

results = {{'Company A': {'Feature 1' : 'On', 'Feature 2': 'Off', 'Feature 
3': 'On'}, 'Company B': {'Feature 1' : 'Off', 'Feature 2': 'On', 'Feature 
3': 'Off'}}}

2 个答案:

答案 0 :(得分:0)

Companies = ['Company A', 'Company B']
features = ['Feature 1', 'Feature 2', 'Feature 3']
values = [['On', 'Off', 'On'], ['Off', 'On', 'Off']]
results = {}

for i in range(len(Companies)):
    results[Companies[i]] = dict(zip(features,values[i]))

print (results)

输出:

{“公司A”:{“功能3”:“开启”,“功能2”:“关闭”,“功能1”:“开启”},“公司B”:{“功能3”:“关闭”,“功能2”:“打开”,“功能1”:“关闭”}}

答案 1 :(得分:0)

您可以使用字典理解:

results = {comp: {feat: v for feat,v in zip(features,val)} for comp,val in zip(Companies,values)}

输出:

{'Company A': {'Feature 1': 'On', 'Feature 2': 'Off', 'Feature 3': 'On'}, 'Company B': {'Feature 1': 'Off', 'Feature 2': 'On', 'Feature 3': 'Off'}}