I have a python dictionary which a have to reorganize the data in a different representation.
current_dict:
{
"1384": {
"Calcium": {
"0-20": {
"id": 2079
}
}
},
"1387": {
"Calcium": {
"0-20": {
"id": 1798
}
}
},
"1397": {
"Calcium": {
"0-20": {
"id": 1586
}
}
}
So I have to reorganize this dict grouping the elements Calcium, its inner deeps and ids and also the outer ids in the following representation:
desired output:
{
"Calcium": {
"0-20": [
{
"Area_id": 1384,
"Intepolation_id": 2079
},
{
"Area_id": 1387,
"Intepolation_id": 1798
},
{
"Area_id": 1397,
"Intepolation_id": 1586
}
]
}
How exactly can I accomplish that? In addition, could you recommend me what should I study to understand better how to create this kind of algorithms? I've been trying to fix this problem for quite some time and all the examples I find on internet about dicts are pretty vague and basic.
CodePudding user response:
Try:
dct = {
"1384": {"Calcium": {"0-20": {"id": 2079}}},
"1387": {"Calcium": {"0-20": {"id": 1798}}},
"1397": {"Calcium": {"0-20": {"id": 1586}}},
}
out = {}
for k, v in dct.items():
for kk, vv in v.items():
for kkk, vvv in vv.items():
out.setdefault(kk, {}).setdefault(kkk, []).append(
{"Area_id": int(k), "Interpolation_id": vvv["id"]}
)
print(out)
Prints:
{
"Calcium": {
"0-20": [
{"Area_id": 1384, "Itnterpolation_id": 2079},
{"Area_id": 1387, "Itnterpolation_id": 1798},
{"Area_id": 1397, "Itnterpolation_id": 1586},
]
}
}