首页 > 解决方案 > 列表中的嵌套字典

问题描述

我在列表中有 2 份字典。在开始时,每个字典都是相同的,并且有一些键/值和一个键与另一个字典。我想更改最后一个字典的值,以便它们在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]

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

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-----------------------

我目前的方法是将复杂的结构传递给单独的字典(结果),然后将它们组合成(结果)并将它们传递给原始字典。

标签: pythonlistdictionarynested-lists

解决方案


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

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

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

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


推荐阅读