我有两个列表:
ramp_versions=['RAMPS_1_6','RAMPS_10','RAMPS_11','RAMPS_7','RAMPS_8_9']
columns=['Version','Date','Total_Ramps','Virtual_Ramps','Real_Ramps','Real_Ramps_With_All_Measurements','Real_Ramps_Unsurveyable','Real_Ramps_Partial_With_999','Real_Ramps_Partial_WO_999','Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD']
我想创建一个嵌套的字典,其中每个ramp_version是一个键,值是一个字典,其中列中的每个值是一个键
这就是我所追求的:
{'RAMPs_1_6': {'Version': "value",'Date': "value", 'Total_Ramps': "value", etc..},'RAMPS_10': {'Version': "value",'Date': "value", 'Total_Ramps': "value", etc..}
答案 0 :(得分:3)
使用字典理解:
{ver: {col: "value" for col in columns} for ver in ramp_versions}
输出:
{'RAMPS_1_6': {'Version': 'value',
'Date': 'value',
'Total_Ramps': 'value',
'Virtual_Ramps': 'value',
'Real_Ramps': 'value',
'Real_Ramps_With_All_Measurements': 'value',
'Real_Ramps_Unsurveyable': 'value',
'Real_Ramps_Partial_With_999': 'value',
'Real_Ramps_Partial_WO_999': 'value',
'Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD': 'value'},
'RAMPS_10': {'Version': 'value',
'Date': 'value',
'Total_Ramps': 'value',
'Virtual_Ramps': 'value',
'Real_Ramps': 'value',
'Real_Ramps_With_All_Measurements': 'value',
'Real_Ramps_Unsurveyable': 'value',
'Real_Ramps_Partial_With_999': 'value',
'Real_Ramps_Partial_WO_999': 'value',
'Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD': 'value'},
'RAMPS_11': {'Version': 'value',
'Date': 'value',
'Total_Ramps': 'value',
'Virtual_Ramps': 'value',
'Real_Ramps': 'value',
'Real_Ramps_With_All_Measurements': 'value',
'Real_Ramps_Unsurveyable': 'value',
'Real_Ramps_Partial_With_999': 'value',
'Real_Ramps_Partial_WO_999': 'value',
'Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD': 'value'},
'RAMPS_7': {'Version': 'value',
'Date': 'value',
'Total_Ramps': 'value',
'Virtual_Ramps': 'value',
'Real_Ramps': 'value',
'Real_Ramps_With_All_Measurements': 'value',
'Real_Ramps_Unsurveyable': 'value',
'Real_Ramps_Partial_With_999': 'value',
'Real_Ramps_Partial_WO_999': 'value',
'Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD': 'value'},
'RAMPS_8_9': {'Version': 'value',
'Date': 'value',
'Total_Ramps': 'value',
'Virtual_Ramps': 'value',
'Real_Ramps': 'value',
'Real_Ramps_With_All_Measurements': 'value',
'Real_Ramps_Unsurveyable': 'value',
'Real_Ramps_Partial_With_999': 'value',
'Real_Ramps_Partial_WO_999': 'value',
'Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD': 'value'}}
答案 1 :(得分:0)
另一个版本:
nest = {}
for r in ramp_versions:
nest[r] = dict(zip(columns, ['val' for x in columns]))
答案 2 :(得分:0)
只需对键运行一个循环并在一个空的已定义字典中为其设置值
请参见以下示例:
ramp_versions=['RAMPS_1_6','RAMPS_10','RAMPS_11','RAMPS_7','RAMPS_8_9']
columns=['Version','Date','Total_Ramps','Virtual_Ramps','Real_Ramps','Real_Ramps_With_All_Measurements','Real_Ramps_Unsurveyable','Real_Ramps_Partial_With_999','Real_Ramps_Partial_WO_999','Real_Ramps_Partial_W_RAMP_WIDTH_<36_or_DWS_BAD']
my_dict = {}
i=0
for ramp in ramp_versions:
my_dict[ramp] = columns[i]
i+=1
print(my_dict)
# print(my_dict.keys())
# print(my_dict.values())