Dynamic Keyboard Key Manipulation

I need to manipulate a dynamic dictionary in python. I have unrecognized information from the input, as in this example:

   'properties[props][defaultValue]': ''
   'properties[props][dt_precision]': ''
   'properties[props][dt_table]': ''
   'properties[props][dtfield]': ''

I need to convert to a dictionary, as in this example:

properties['props']['dt_table'] = 1
properties['props']['dt_table'] = 2

I do not know the real information, but I know that the format is as follows:

variable[index] = value 
variable[index][index_1] = value
variable[index][index_1] [index_2]= value
variable[index][index_1] [index_2][index_3]= value

My problem is how can I add a dictionary with infinite key layers? In other words, dynamically add a large hierarchy of connections to subsections.

In javascript, I use links like this:

f=var['key'];
f['key'] = {};
f = f['key'];
f['key'] = 120;

Which allows me to build:

var['key']['key'] = 120

but the equivalent in python does not work.

+4
source share
1 answer

Naive approach

- :

var = {}
var['key'] = {}
var['key']['key'] = 120

print(var['key']['key'])
print(var)

:

120
{'key': {'key': 120}}

Autovivification

, defaultdict, @martineau :

from collections import defaultdict

def tree():
    return defaultdict(tree)

v2 = tree()
v2['key']['key'] = 120

print(v2['key']['key'])
print(v2)

:

120
defaultdict(<function tree at 0x1ae7d88>, {'key': defaultdict(<function tree at 0x1ae7d88>, {'key': 120})})
+2

Source: https://habr.com/ru/post/1607881/


All Articles