【发布时间】:2023-01-20 04:46:11
【问题描述】:
我想将元素添加到嵌套的 python 字典中
res_checks = dict()
res_checks['arg1']['sub1'] = 'test'
print(res_checks)
但我总是得到这个错误
Traceback (most recent call last):
File "main.py", line 2, in <module>
res_checks['arg1']['sub1'] = 'test'
KeyError: 'arg1'
尝试以不同的格式添加它,但总是失败
【问题讨论】:
-
res_checks.setdefault('arg1', {})['sub1'] = 'test'。更好的是,res_checks = collections.defaultdict(dict) -
这回答了你的问题了吗? Create nested dictionary on the fly in Python
-
先做
res_checks['arg1'] = {}会解决你的问题
标签: python dictionary