0

I want to add lements to nested python dictionary

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

print(res_checks)

but I always get this error

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    res_checks['arg1']['sub1'] = 'test'
KeyError: 'arg1'

try to add it in different formats but it is always fail

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

0

Python doesn't know that res_checks['arg1'] is supposed to be a dictionary, so it can't index it. You have to declare it as an empty dictionary first.

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

print(res_checks)
Michael Cao
  • 2,278
  • 1
  • 1
  • 13
0

For a one-shot approach:

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

print(res_checks)

Result:

{'arg1': {'sub1': 'test'}}
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53