I have input dictionary like:
{
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
},
]
}
and I want to group the same values of key objType
to generate the dict as below
{
"objects": [
{
"objType": "master",
"objDetails": [
{
"objName": "sampleOne",
"ObjectTitle": "Sample One"
},
{
"objName": "sampleTwo",
"ObjectTitle": "Sample Two"
}
]
]
}
I have used pandas groupby but not able to get the desired output.
I am not sure pandas is appropriate for what you want to accomplish, given the multi=tiered structure o your data. The following function will correctly parse your data, base on your example input and desired output.
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}
Given input of
di = {
"objects": [
{
"objType": "master",
"objName": "sampleOne",
"objTitle": "Sample One"
},
{
"objType": "master",
"objName": "sampleTwo",
"objTitle": "Sample Two"
}
]
}
transform(di)
produces:
{'objects':
{'master': [{'objName': 'sampleOne', 'ObjectTitle': 'Sample One'},
{'objName': 'sampleTwo', 'ObjectTitle': 'Sample Two'}]}}