我想转换为特定的嵌套字典格式。 数据帧df如下所示:
OC OZ ON WT DC DZ DN
0 PL 97 TP 59 DE 63 DC
3 US 61 SU 9 US 95 SU
预期输出如下:
{'location':
{
'zipCode':
{'country': 'PL',
'code': '97'},
'location': {'id': '1'},
'longName': 'TP',
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'load':
{'weight': '59',
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
},
{'location':
{
'zipCode':
{'country': 'DE',
'code': '63'},
'location': {'id': '2'},
'longName': 'DC']
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'unload': {
'weight': '59'),
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
}
我尝试了下面的代码,但只得到字典的一部分:
dic = {}
dic['section'] = []
for ix, row in df.iterrows():
in_dict1 = {
'location':
{
'zipCode':
{'country': row['OC'],
'code': row['OZ']},
'location': {'id': '1'},
'longName': row['ON'],
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'load':
{'weight': str(row['WT']),
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
},
in_dict2 = {'location':
{
'zipCode':
{'country': row['DC'],
'code': row['DZ']},
'location': {'id': '2'},
'longName': row['DN']
},
'CarriageParameter':
{'road':
{'truckLoad': 'Auto'}
},
'unload': {
'weight': str(row['WT']),
'unit': 'ton',
'showEmissionsAtResponse': 'true'
}
}
dic['section'].append(in_dict1)
下面第一行的漂亮字体:
{'section': [{'CarriageParameter': {'road': {'truckLoad': 'Auto'}},
'load': {'showEmissionsAtResponse': 'true',
'unit': 'ton',
'weight': '59'},
'location': {'location': {'id': '1'},
'longName': 'TP COLEP_GRABICA PL',
'zipCode': {'code': '97-306', 'country': 'PL'}}}]}
我希望字典的第二部分在某个地方丢失了
如何解决这个问题
因为您没有添加第二本词典,您可以尝试以下方法:
输出:
相关问题 更多 >
编程相关推荐