0

If I have a nested dictionary and varying lists:

d = {'a': {'b': {'c': {'d': 0}}}}
list1 = ['a', 'b']
list2 = ['a', 'b', 'c']
list3 = ['a', 'b', 'c', 'd']

How can I access dictionary values like so:

>>> d[list1]
{'c': {'d': 0}}
>>> d[list3]
0
2
  • 1
    while not a strict duplicate, this is a close match: stackoverflow.com/q/31033549/758174 Commented Oct 12, 2022 at 20:14
  • good point, couldn't find that googling! Commented Oct 12, 2022 at 21:06

2 Answers 2

7

you can use functools reduce. info here. You have a nice post on reduce in real python

from functools import reduce

reduce(dict.get, list3, d)
>>> 0

EDIT: mix of list and dictioanries

in case of having mixed list and dictionary values the following is possible

d = {'a': [{'b0': {'c': 1}}, {'b1': {'c': 1}}]}
list1 = ['a', 1, 'b1', 'c']

fun = lambda element, indexer: element[indexer]
reduce(fun, list1, d)
>>> 1
Sign up to request clarification or add additional context in comments.

5 Comments

This is a great answer. But I realize it doesn't work if you have lists in your dictionary like so d = {'a': [{'b0': {'c': 1}}, {'b1': {'c': 1}}]} and a list like so ['a', 1, 'c']
It is possible let me make an edit
actually is possible if your list is as follow ['a', 1, 'b1' 'c'], would that pass? In any case I have added an edit
legendary .....
you can check the real python post whenever you have time, is quite nice, reduce can be very useful!
2

Use a short function:

def nested_get(d, lst):
    out = d
    for x in lst:
        out = out[x]
    return out

nested_get(d, list1)
# {'c': {'d': 0}}

Comments

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.