首页 > 解决方案 > 创建带值的字典时,任意将值从 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}}

标签: pythondictionaryboolean

解决方案


您正在将对象分配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()


推荐阅读