我想設計一個自動生成的詞典模板。字典的格式是這樣的:{'google_drive': {'services': []}, 'dropbox': {'services': []}, 'test': {'services': []}}所有鍵具有相同的值,并且其值 ID/地址應不同?,F在的問題是所有值都是相同的。{'services': []}# init function has an array ["google_drive", "dropbox", "test"] # so that all the key-value pairs can be created automaticallytest = CloudInfo().init().config_infoprint(id(test["google_drive"]["services"]))print(id(test["dropbox"]["services"]))print(id(test["test"]["services"]))輸出238275608121623827560812162382756081216我在封裝的方法中發現了問題:def update_all_value(self, keys, value): __keys = keys __dict = self.__dict __value = value if __keys is not None: for key in __keys: if key in __dict: __dict.update({key: __value}) self.__dict = __dict return self所有鍵都指向單個變量 。__value如果我更改為 ,字典值是不同的 id。但該函數不可重用。__dict.update({key: __value})__dict.update({key: {'services': []}})有沒有好的解決方案可以更新具有不同ID的所有字典值并保持輸入參數的工作?value
1 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
您可以使用默認命令:
from collections import defaultdict
import copy
template = {'services': []}
test = defaultdict(lambda: copy.deepcopy(template))
print(id(test["google_drive"]["services"]))
# 2546846465416
print(id(test["dropbox"]["services"]))
# 2546847840648
print(id(test["test"]["services"]))
# 2545171504392
添加回答
舉報
0/150
提交
取消