Python 在 2D 字典中追加值

Python append value in 2D Dictionary

我有以下字典,我想再追加一个数组到 'CorrectionsAll'。我试过追加选项,但我无法得到我需要的东西。有人可以帮我解释一下逻辑吗。

Dict1 = {'ShpmtID': 123, 'PickupDate': '2016/01/01 00:00:00', 'EstimatedDeliveryDate': '2016/01/10 00:00:00', 'OrigSic': 'LJB', 'DestSic': 'XCF', 'CorrectionHistory': [{'key': 405013, 'CorrectionsAll': [{'CorrChngDesc': 'Commodity Line Changed'}]}]}

想添加"Discount Line changed"如下:

{'ShpmtID': 123, 'PickupDate': '2016/01/01 00:00:00', 'EstimatedDeliveryDate': '2016/01/10 00:00:00', 'OrigSic': 'LJB', 'DestSic': 'XCF', 'CorrectionHistory': [{'key': 405013, 'CorrectionsAll': [{'CorrChngDesc': 'Commodity Line Changed'}, {'CorrChngDesc': 'Discount Line Changed'}]}]}

Copy Comment: tried these two options:

选项-1:

Dict1["CorrectionHistory"]["CorrectionsAll"].append({'CorrChngDesc': 'Discount Line Changed'})  

选项 2:

Dict1["CorrectionsAll"].append({'CorrChngDesc': 'Discount Line Changed'})

您只需访问所需的列表,然后附加到该列表即可

Dict1['CorrectionHistory'][0]['CorrectionsAll'].append({'CorrChngDesc': 'Discount Line Changed'})

输出:

{'OrigSic': 'LJB', 'PickupDate': '2016/01/01 00:00:00', 'DestSic': 'XCF', 'ShpmtID': 123, 'CorrectionHistory': [{'key': 405013, 'CorrectionsAll': [{'CorrChngDesc': 'Commodity Line Changed'}, {'CorrChngDesc': 'Discount Line Changed'}]}], 'EstimatedDeliveryDate': '2016/01/10 00:00:00'}

I tried these two options: Option-1: Dict1["CorrectionHistory"]["CorrectionsAll"].append({'CorrChngDesc': 'Discount Line Changed'})

Option-1 不起作用,因为 "CorrectionAll" 不是 "CorrectionHistory" 的元素,而是列表的元素。不过,该列表是其中的一个元素。

Dict1["CorrectionHistory"][0]["CorrectionsAll"] # Use [0] to go inside this list !

Option-2: Dict1["CorrectionsAll"].append({'CorrChngDesc': 'Discount Line Changed'})

选项 2 也不起作用,因为 Dict1["CorrectionAll"] 不存在。又是它,不是它的直接元素,但我想你现在可以理解为什么了。