列表中的嵌套字典

Nested dictionaries on list

我在列表中有 2 份字典。在开始时,每本字典都是相同的,并且有一些 keys/values 和一个键与另一本字典。我想更改最后一个字典的值,使它们在 list[0] 字典和 list[1] 字典上不同。结构是:

list = [dictionary{key1:values.., key2:dictionary{key3:values}}, dictionary{key1:values.., key2:dictionary{key3:values}}]

我想更改 list[0][key2][key3] 值而不影响 list[1][key2][key3]

请注意,这是对原始数据的简化,因为列表已经是第一个字典中的值...(在代码中,列表是 'predictions' 的值)

data = {'id': 6, 'data': {'image': '/data/upload/0_egghdRx.jpg'}, 'annotations': [], 'predictions': [{'id': 7, 'result': [{'original_width': 1280, 'original_height': 720, 'image_rotation': 0, 'value': {'x': 37.2, 'y': 31.990521327014218, 'width': 12.266666666666667, 'height': 11.137440758293838, 'rotation': 0, 'rectanglelabels': ['Person']}, 'id': 'KzkuSDEToK', 'from_name': 'label', 'to_name': 'image', 'type': 'rectanglelabels'}]}]}
#list to store dicts
results = []

#Copy dict and change 2 values
result = data['predictions'][0]['result'][0].copy()
result['original_width'] = 100
result['value']['x'] = 100

results.append(result)
print(results)

#Copy dict and change 2 values
result = data['predictions'][0]['result'][0].copy()
result['original_width'] = 200
result['value']['x'] = 200

results.append(result)

print(results)
#Now I try to change the original dictionary
data['predictions'][0]['result'] = results
print('----------------------------END-----------------------')

执行这段代码的结果是(抱歉输出丑陋):

[{'original_width': 100, 'original_height': 720, 'image_rotation': 0, 'value': {'x': 100, 'y': 31.990521327014218, 'width': 12.266666666666667, 'height': 11.137440758293838, 'rotation': 0, 'rectanglelabels': ['Person']}, 'id': 'KzkuSDEToK', 'from_name': 'label', 'to_name': 'image', 'type': 'rectanglelabels'}]
....................................................
[{'original_width': 100, 'original_height': 720, 'image_rotation': 0, 'value': {'x': 200, 'y': 31.990521327014218, 'width': 12.266666666666667, 'height': 11.137440758293838, 'rotation': 0, 'rectanglelabels': ['Person']}, 'id': 'KzkuSDEToK', 'from_name': 'label', 'to_name': 'image', 'type': 'rectanglelabels'}, {'original_width': 200, 'original_height': 720, 'image_rotation': 0, 'value': {'x': 200, 'y': 31.990521327014218, 'width': 12.266666666666667, 'height': 11.137440758293838, 'rotation': 0, 'rectanglelabels': ['Person']}, 'id': 'KzkuSDEToK', 'from_name': 'label', 'to_name': 'image', 'type': 'rectanglelabels'}]
----------------------------END-----------------------

我目前的做法是将复杂的结构传递给分离的字典(result),然后将它们组合在(result)中,传递给原始字典。

问题在于您使用了创建列表浅表副本的 list.copy() 函数。它创建了一个新列表,但随后插入了对原始列表中对象的引用。

相反,如果您想要独立副本,您应该创建一个深层副本:

import copy
result = copy.deepcopy(data['predictions'][0]['result'][0])`

https://docs.python.org/3/library/copy.html#copy.deepcopy