1

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

1
  • have you tried addict.Dict - that's probably the easiest way. Otherwise of course you can iterate with .get() Commented Jan 28, 2015 at 18:46

2 Answers 2

1

Iteratively go into the subdictionaries.

result = dictionary
for key in keys:
  result = result[key]
print(result)
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

You should try, except or use get and break on None.
Why? keys is supposed to be a list of valid keys. If it contains one that does not exist, I would expect a KeyError to be raised. Suppressing this error would only lead to problems down the line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.