OrangePot
OrangePot

Reputation: 1082

Access dictionary values using list values as subsequent keys

keys = ['prop1', 'prop2', 'prop3']
dict = { prop1: { prop2: { prop3: True } } }

How do I get the value True out of the dict using the list?

Not having any success with

val = reduce((lambda a, b: dict[b]), keys)

update:

keys and dict can be arbitrarily long, but will always have matching properties/keys.

Upvotes: 2

Views: 49

Answers (2)

Geeocode
Geeocode

Reputation: 5797

EDIT: As Op. rephrased his question, I made an update:

Actually you don't need for keys at all to get "True". You can use a recursive function to do it nicely without knowing the keys.

d = { 'prop1': { 'prop2': { 'prop3': True } } }

def d_c(dc):
    if isinstance(list(dc.values())[0], dict):
        return d_c(list(dc.values())[0])
    return list(dc.values())[0]

Result:

True

Upvotes: 1

wim
wim

Reputation: 362786

Using a loop:

>>> a = ['prop1', 'prop2', 'prop3'] 
>>> d = {'prop1': {'prop2': {'prop3': True}}}
>>> result = d
>>> for k in a: 
...     result = result[k] 
...
>>> result
True

Using a functional style:

>>> from functools import reduce
>>> reduce(dict.get, a, d)
True

Upvotes: 3

Related Questions