0

Let's say I have a dictionary like this

{
    "level1": {
        "stuff": 1, 
        "morestuff": 2, 
        "otherstuff": {
            "this": 9.2 
        } 
    }
}

And I have a list of keys like this ['level1'] or ['level1', 'stuff'].

Right now, my solution is find the length of the list and pass the keys given their number

if len(dictionary) == 1 : 
     return dictionary['level1'] 
elif len(dictionary) == 2 : 
     return dictionary['level1']['morestuff'] 
... 

Is there a way to pass the keys dynamically to explore the dictionary?

  • Python dictionaries have many methods that are useful here. [Check the docs](https://docs.python.org/3/library/stdtypes.html#typesmapping). Most notably, `.keys()`, `list(dict)` or `iter(dict)`. – Liftoff Jun 10 '21 at 07:49
  • 2
    Does this answer your question? [Access nested dictionary items via a list of keys?](https://stackoverflow.com/questions/14692690/access-nested-dictionary-items-via-a-list-of-keys) – leaf_yakitori Jun 10 '21 at 07:51
  • I'd suggest the second answer, https://stackoverflow.com/a/37704379/683329; the first answer with `reduce` is impenetrable... – Jiří Baum Jun 10 '21 at 07:55

0 Answers0