Andrius Andrius - 2 months ago 17
Python Question

Python: dynamically accessing nested dictionary keys?

Is there some simple way to access nested dictionary key when at first you don't know which key you will be accessing?

For example:

dct = {'label': 'A', 'config': {'value': 'val1'}}


In this dictionary I will need to access either
label
key or
value
key inside another dict that is accessible through
config
key.

It depends on state.

For example if we have variable called
label
, so if:

label = True
if label:
key = 'label'


in this case its kind of easy:

dct[key]


Now if label is false and I need to access nested dictionary, how can I dynamically specify it so I would not need to use ifs on every iterated item (I mean check everytime if
label
is used instead of
value
, because I will know that before starting iteration on dictionary full of
dct
dictionaries)?

like:

label = False
if label:
key = 'label'
else:
key = 'config..?' # it should be something like ['config']['value']

Answer

If you know the key to be traversed, you can try out the following. This would work for any level of nested dicts.

dct = {'label': 'A', 'config': {'value': 'val1'}}

label = True
key = ('label',)
if not label:
    key = ('config', 'value')

ret = dct
for k in key:
  ret = ret[k]

print ret
Comments