TAGS :Viewed: 1 - Published at: a few seconds ago

[ Use list items as keys for nested dictionary ]

I want to use the items in a list as dictionary keys to find a value in nested dictionaries.

For example, given the following list:

keys = ['first', 'second', 'third']

I want to do:

result = dictionary[keys[0]][keys[1]][keys[2]]

Which would be the equivalent of:

result = dictionary['first']['second']['third']

But I don't know how many items will be in the keys list beforehand (except that it will always have at least 1).

Answer 1


Iteratively go into the subdictionaries.

result = dictionary
for key in keys:
  result = result[key]
print(result)

Answer 2


A simple for-loop will work:

result = dictionary[keys[0]]  # Access the first level (which is always there)
for k in keys[1:]:            # Step down through any remaining levels
    result = result[k]

Demo:

>>> dictionary = {'first': {'second': {'third': 123}}}
>>> keys = ['first', 'second', 'third']
>>> result = dictionary[keys[0]]
>>> for k in keys[1:]:
...     result = result[k]
...
>>> result
123
>>>