我有一个这样的输入字典:
{
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
},
]
}
和我想将键objType
的相同值分组以生成如下
{
"objects": [
{
"objType": "master",
"objDetails": [
{
"objName": "sampleOne",
"ObjectTitle": "Sample One"
},
{
"objName": "sampleTwo",
"ObjectTitle": "Sample Two"
}
]
]
}
我使用了pandas groupby,但是没有得到想要的输出。
考虑到数据的多层结构,我不确定pandas是否适合您想要完成的任务。下面的函数将根据示例输入和期望输出正确解析数据。
def transform(di):
tmp = dict()
for ntry in di['objects']:
tval = tmp.pop(ntry['objType'], [])
indict = dict()
indict['objName'] = ntry['objName']
indict['ObjectTitle'] = ntry['objTitle']
tval.append(indict)
tmp[ntry['objType']] = tval
return {'objects': tmp}
给定输入
di = {
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
}
]
}
transform(di)
生产:
{'objects':
{'master': [{'objName': 'sampleOne', 'ObjectTitle': 'Sample One'},
{'objName': 'sampleTwo', 'ObjectTitle': 'Sample Two'}]}}