创建带有值的字典时,值从 False 任意更改为 True

When creating a dictionary with values, the value is arbitrarily changed from False to 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 分配给您的字典键 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

使用 dict_gate 而不是 dict_gate.copy()

时请注意 ID