python - 创建带值的字典时,任意将值从 False 更改为 True
问题描述
有必要形成一个字典作为一组字典的参数。在这些字典中有一个名为“reverse”的键。此键默认设置为 False。添加字典时,我会根据某些条件更改“反向”键的值。但由于某种原因,在一般源语词汇中,“反向”的意思只改变为真理报。
为什么意义随意变化,在什么地方变化?
# -*- coding: utf-8 -*-
struct_state_devices = None
dict_gate = {"state_gate": {},
"position": {"state": "", "stop": False},
"reverse": False,
}
test_list = [{"device_code": "1111", "reverse": False}, {"device_code": "2222", "reverse": True}]
if struct_state_devices is None:
struct_state_devices = dict()
for dev in test_list:
struct_state_devices[dev["device_code"]] = dict_gate # добавление словаря устройства
print("before: " + str(struct_state_devices))
for dev in test_list:
if dev["reverse"] is True:
struct_state_devices[dev["device_code"]]["reverse"] = True
# print(self.struct_state_devices[dev.device_code]['reverse'])
print("after: " + str(struct_state_devices))
输出:
before: {'1111': {'state_gate': {}, 'position': {'state': '', 'stop': False}, 'reverse': False}, '2222': {'state_gate': {}, 'position': {'state': '', 'stop': False}, 'reverse': False}}
after: {'1111': {'state_gate': {}, 'position': {'state': '', 'stop': False}, 'reverse': True}, '2222': {'state_gate': {}, 'position': {'state': '', 'stop': False}, 'reverse': True}}
解决方案
您正在将对象分配dict_gate
给您的 dict keys struct_state_devices[dev['device_code']]
。当您将该对象内的值更改为其他值时,您也在为所有其他值更改它。
试试这个:
for dev in test_list:
struct_state_devices[dev["device_code"]] = dict_gate.copy()
明白了吗:
>>> for dev in test_list:
struct_state_devices[dev['device_code']] = dict_gate
>>> id(dict_gate)
1267141041832
>>> id(struct_state_devices['1111'])
1267141041832
>>> for dev in test_list:
struct_state_devices[dev['device_code']] = dict_gate.copy()
>>> id(struct_state_devices['1111'])
1267141285912
>>> id(struct_state_devices['2222'])
1267141286232
使用时注意ID,dict_gate
而不是dict_gate.copy()
推荐阅读
- amazon-web-services - aws 私有子网访问
- vb.net - 表单之间的启动画面
- python - 没有名为“glob2”的模块
- javascript - 你如何用winston捕捉`错误:ENOENT:没有这样的文件或目录`?
- node.js - Passport Facebook 身份验证返回未定义?
- vba - 字符串案例的不选择案例的案例
- c - Knight tours算法C实现性能
- python - TypeError:尝试运行机器人命令时,“str”对象不可调用
- html - 悬停在父级上以触发变换属性
- python - ValueError:无法为有效的 JSON 文件解码任何 JSON 对象