【问题标题】:failed to add elements directly to python nested dictionarypython嵌套字典直接添加元素失败
【发布时间】: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


【解决方案1】:

Python 不知道 res_checks['arg1'] 应该是一个字典,所以它不能索引它。您必须先将其声明为空字典。

res_checks = dict()
res_checks['arg1'] = {}
res_checks['arg1']['sub1'] = 'test'

print(res_checks)

【讨论】:

    【解决方案2】:

    尝试:

    res_checks = dict(arg1={'sub1': 'test'})
    
    print(res_checks)
    

    出去:

    {'arg1': {'sub1': 'test'}}
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 2023-01-22
      • 2023-02-05
      • 2018-11-07
      • 2015-03-24
      • 1970-01-01
      • 2016-12-10
      • 2018-04-25
      • 2015-06-14
      相关资源
      最近更新 更多