There is a dictionary of dictionaries:

a = {'a': {'b': {'c': {}}, 'd': {'e': {}}}} 

And there is a list / tappl:

 f = ('a', 'b', 'c') #or ['a', 'b', 'c'] 

How can you implement the following indexing with the help of the same tapl:

 a['a']['b']['c'] = 'here' print(a['a']['b']['c'] ) # -> 'here' 

help me please!

That is, we do not know what is in the dictionary and what is in the tapl. But we know for sure that there is exactly the way to the meaning we need in the tuple. And you need to be able to change the very dictionary (namely, the value)

3 answers 3

If you have a nested dictionary:

 nested_dict = {'a': {'b': {'c': {}}, 'd': {'e': {}}}} 

And the appropriate path:

 path = 'a', 'b', 'c' 

That assignment can be implemented as:

 from functools import reduce # nested_dict['a']['b']['c'] = 'here' *keys, newkey = path reduce(dict.__getitem__, keys, nested_dict)[newkey] = 'here' 

See Change values ​​in dict of nested dicts using items in a list?

Similarly, reading the value along the way:

 # print(nested_dict['a']['b']['c'] ) # -> 'here' print(reduce(dict.__getitem__, path, nested_dict)) # -> here 

See Is it possible to store "path" in lists and dictionaries in a variable?

    Getting the value:

     from functools import reduce value = reduce(lambda c, k: c[k], f, a) 

    Assignment is harder. Solution to the forehead:

     c = a for n, k in enumerate(f, start=1): if n == len(f): c[k] = 'here' else: c = c[k] 

    Well, or you can not reinvent the wheel and use dpath , for example.

       >>> from functools import reduce >>> a = {'a': {'b': {'c': {}}, 'd': {'e': {}}}} >>> f = ('a', 'b', 'c') >>> reduce(lambda c,k: c[k], f[:-1], a)[f[-1]]='here' >>> a {'a': {'b': {'c': 'here'}, 'd': {'e': {}}}}