簡體   English   中英

創建帶有值的字典時,將值任意從 False 更改為 True

[英]When creating a dictionary with values, the value is arbitrarily changed from False to True

有必要形成一個字典作為參數,其中有一組字典。 在這些詞典中,有一個名為“reverse”的鍵。 默認情況下,此鍵設置為 False。 添加字典時,我會根據某些條件更改“反向”鍵的值。 但不知為何,在一般的源詞匯中,“逆”的意思只變到了Pravda。

為什么意思隨意變化,在什么地方?

# -*- 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 鍵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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM