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!
2
Answers
Create temporary dictionary from
dct2
to ease the search:Prints:
You’re updating the first dictionary for every second dictionary in the
tracker_detail
list. I would change your code like so:Also, don’t shadow built-ins. Doing that won’t allow you to instantiate a
dict
class anymore.