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...)

0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can go with the intuitive solution:

val = d
for key in k:
   val = val[key]
# operations with val here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.