Home > front end >  How to get to a dict key from a list?
How to get to a dict key from a list?

Time:12-07

lets say I have the following dict structure and a list of keys.

d = {
    'a': {
        'b': {
            'c': 'value'
        }
    }
}
keyList = ['a', 'b', 'c']

What is a pythonic way to reference the value of the c key in a dynamic way? In a static way I would say something like d[a][b][c] however if my keyList is dynamic and I need to reference the value at runtime is there a way to do this? the len of keyList is variable.

The main problem is i really don't know what to search. I tried things like dynamic dictionary path but couldn't get anything remotely close

CodePudding user response:

d = {
    'a': {
        'b': {
            'c': 'value'
        }
    }
}

key_list = ['a', 'b', 'c']

# Use the `get` method to traverse the dictionary and get the value at the specified path
value = d
for key in key_list:
    value = value.get(key, {}) # suggested by @sahasrara62

# Print the value
print(value)  # Output: 'value'

CodePudding user response:

You can use functools.reduce with the input dict as the starting value and dict.get as the reduction function:

from functools import reduce

print(reduce(dict.get, keyList, d))

This outputs:

value

Demo: https://replit.com/@blhsing/QuintessentialAntiqueMath

  • Related