2

I have a a nested dict object with N layers:

d={'l0':{'l1':{'l2':...}}}

in addition, I have a list of all the dict keys:

k=['l0','l1','l2',...]

how can I access the element defined by the list,for an arbitrary list, that is:

d[k[0]][k[1]][k[2]].... = X

(I would like a function that return the reference to the data...)

Mercury
  • 1,886
  • 5
  • 25
  • 44

2 Answers2

3

One approach is the following:

def resolve_value(obj, keys):
    for key in keys:
        obj = obj[key]
    return obj


k = ['l0', 'l1', 'l2']
d = {'l0': {'l1': {'l2': 'hello'}}}

print(resolve_value(d, k))

Output

hello
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

You can go with the intuitive solution:

val = d
for key in k:
   val = val[key]
# operations with val here
kist
  • 590
  • 2
  • 8