python - 列表中的嵌套字典
问题描述
我在列表中有 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-----------------------
我目前的方法是将复杂的结构传递给单独的字典(结果),然后将它们组合成(结果)并将它们传递给原始字典。
解决方案
问题是您使用了一个list.copy()
创建列表的浅表副本的函数。它创建一个新列表,然后插入对原始列表中对象的引用。
相反,如果您想要独立副本,您应该创建一个深层副本:
import copy
result = copy.deepcopy(data['predictions'][0]['result'][0])`
推荐阅读
- python - 字符串包含两个数字之一
- reactjs - 转到 Visual Studio 代码中的定义不适用于组件的 Package.json
- c++ - 让虚方法接受任何 Qt 容器类型作为输入参数
- aws-lambda - AWS 代理:在 lambda 中使用 sequelize 时 RDS 连接限制
- excel - VBA:if Then循环中的语句失败
- r - R 中的矢量回收概念
- qt - QT creator 4.7.4 VS QT creator 4.15.0:菜单图标的大小
- syntax - 在 Ocaml 中找到 **,但不是求幂
- c# - 在 mds 中使用 ValidationProcessAsync 验证创建的实体的问题
- html - HTML 和 CSS 中的标签和单选按钮