我有两个字典列表:
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
},
我想创建一个新字典/用第二个字典更新第一个字典,并根据 2 个条件将“trackerDescription”作为“注释”:1.第一个字典中的 PK 与第二个字典中的 trackerDetailId 和第二个字典中的 trackerType 相同第二个是6。不符合条件的人应该得到一张纸条,上面写着“无纸条”
所需输出:
"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"
}
我的代码在每种情况下都会产生“无注释”。
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'
我将不胜感激任何帮助和提示1 谢谢!
从
dct2
创建临时字典以简化搜索:
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)
打印:
{
"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",
},
]
}
您正在更新 tracker_detail
列表中
每第二个词典的第一个词典。我会像这样更改你的代码:
for dict_bottlefeed in data_dict['baby_bottlefeed']:
for dict_trackerdetail in data_dict['tracker_detail']:
if dict_trackerdetail['trackerType'] == 6 and dict_trackerdetail['trackerDetailId'] == dict_bottlefeed['pk']:
dict_bottlefeed['note'] = dict_trackerdetail['trackerDescription']
break
else:
dict_bottlefeed['note'] = 'no note'
另外,不要隐藏内置函数。这样做将不允许您再实例化
dict
类。