【问题标题】:When creating a dictionary with values, the value is arbitrarily changed from False to True创建带值的字典时,任意将值从 False 更改为 True
【发布时间】:2021-03-03 20:08:39
【问题描述】:

有必要形成一个字典作为参数,其中一组字典。在这些字典中有一个名为“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}}

【问题讨论】:

    标签: python dictionary boolean


    【解决方案1】:

    您正在将对象 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多