-1

Currently I am importing a file as a dictionary with a structure similar to the following:

Dict:
key1
 key2a
  key3a
   value1
   value2
   value3
  key3b
   value1
   value2
   value3
 key2b
 key2c
 

In this instance I need to add a key3c and in each case I need to add a value1, value2, value3 etc. These values need to correspond to the correct location according to the other values under the key3 level.

currently I am trying to the following with no luck

for rownumber in range(len(dict[key1][key2][key3b]):
    dict[key1][key2][key3c][rownumber] = variable

This gives me a syntax error due to key3c not existing yet.

What is the best way to add this key and its values in considering I need to do it whilst iterating over and finding matches to another dictionary?

j.t.2.4.6
  • 178
  • 1
  • 11
  • Does this answer your question? [Creating a tree/deeply nested dict from an indented text file in python](https://stackoverflow.com/questions/17858404/creating-a-tree-deeply-nested-dict-from-an-indented-text-file-in-python) – DarrylG May 20 '22 at 13:50
  • @DarrylG unfortunately I don't think it does, here I already have the dictionary and I need to add new keys with multiple values to it – j.t.2.4.6 May 20 '22 at 14:44
  • "This gives me a syntax error due to key3c not existing yet." - no, because there is a *syntax error*, namely the lack of closing parentheses matching those from `range(len(`. – mkrieger1 May 20 '22 at 15:22

1 Answers1

0

Would be helpful to give a sample dummy data and a sample output. Better yet a runnable chunk of code on top. Also direct print out of your error... Anyhow, based on my interpretation see below

import json

### create dummy dict
dic  = {'key1': {'key2a': {'key3a': ['value1','value2','value3'],
                          'key3b': ['value1','value2','value3']},
               'key2b': None,
               'key2c': None}
      }


### print dummy
print(json.dumps(dic ,sort_keys=True, indent=2))

Outputs:

enter image description here


### add nested new key and values 
dic['key1']['key2a']['key3c'] = ['value1','value2','value3']

### print resultant
print(json.dumps(dic ,sort_keys=True, indent=2))

Outputs

enter image description here

Yev Guyduy
  • 1,371
  • 12
  • 13