I have two lists of dictionaries:
1.
"baby_bottlefeed" : [
{
"pk" : 1,
"amountML" : 22.600000381469727,
"isFormula" : 1,
"babyid" : 1,
"date" : 1688970600
},
{
"pk" : 2,
"amountML" : 50,
"isFormula" : 1,
"babyid" : 1,
"date" : 1689132692.5657411
},
{
"pk" : 3,
"amountML" : 50,
"isFormula" : 1,
"babyid" : 1,
"date" : 1689171473.9392519
},
"tracker_detail" : [
{
"trackerDetailId" : 1,
"trackerDescription" : "some note1",
"trackerType" : 6,
"babyId" : 1
},
{
"trackerDetailId" : 3,
"trackerDescription" : "some note2",
"trackerType" : 11,
"babyId" : 1
},
I want to create a new dictionary/update the first one with the second one with "trackerDescription" as a "note" based on 2 condition: 1. PK from the 1st one is the same as trackerDetailId from the second one and trackerType from 2nd one is 6. The ones that does not the condition should get a note saying "no note"
Desired output:
"baby_bottlefeed" : [
{
"pk" : 1,
"amountML" : 22.600000381469727,
"isFormula" : 1,
"babyid" : 1,
"date" : 1688970600,
"note" : "some note1"
},
{
"pk" : 2,
"amountML" : 50,
"isFormula" : 1,
"babyid" : 1,
"date" : 1689132692.5657411,
"note" : "no note"
},
{
"pk" : 3,
"amountML" : 50,
"isFormula" : 1,
"babyid" : 1,
"date" : 1689171473.9392519
"note" : "no note"
}
my code produces "no note" in every case.
for dict in data_dict['baby_bottlefeed']:
for dict_trackerdetail in data_dict['tracker_detail']:
dict['note'] = dict_trackerdetail['trackerDescription'] if (
dict_trackerdetail['trackerType'] == 6 and dict_trackerdetail['trackerDetailId'] == dict['pk']) else 'no note'
i will appreciate any help and tips1 Thank you!
Create temporary dictionary from dct2
to ease the search:
dct1 = {
"baby_bottlefeed": [
{
"pk": 1,
"amountML": 22.600000381469727,
"isFormula": 1,
"babyid": 1,
"date": 1688970600,
},
{
"pk": 2,
"amountML": 50,
"isFormula": 1,
"babyid": 1,
"date": 1689132692.5657411,
},
{
"pk": 3,
"amountML": 50,
"isFormula": 1,
"babyid": 1,
"date": 1689171473.9392519,
},
]
}
dct2 = {
"tracker_detail": [
{
"trackerDetailId": 1,
"trackerDescription": "some note1",
"trackerType": 6,
"babyId": 1,
},
{
"trackerDetailId": 3,
"trackerDescription": "some note2",
"trackerType": 11,
"babyId": 1,
},
]
}
tmp = {
td["trackerDetailId"]: td for td in dct2["tracker_detail"] if td["trackerType"] == 6
}
for bb in dct1["baby_bottlefeed"]:
if bb["pk"] in tmp:
bb["note"] = tmp[bb["pk"]].get("trackerDescription")
else:
bb["note"] = "no note"
print(dct1)
Prints:
{
"baby_bottlefeed": [
{
"pk": 1,
"amountML": 22.600000381469727,
"isFormula": 1,
"babyid": 1,
"date": 1688970600,
"note": "some note1",
},
{
"pk": 2,
"amountML": 50,
"isFormula": 1,
"babyid": 1,
"date": 1689132692.565741,
"note": "no note",
},
{
"pk": 3,
"amountML": 50,
"isFormula": 1,
"babyid": 1,
"date": 1689171473.939252,
"note": "no note",
},
]
}