1

I'm trying to figure out how I can reference nested dict keys as a variable. For example, I have a nested dict of type:

example =  {'a': {'b': 'hi'}, 'c': 1}

I would like to do something like:

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

for key in keys:
    print(example[key])

Output I would expect:

1
hi
keynesiancross
  • 3,441
  • 15
  • 47
  • 87
  • 1
    There's no single key you can use to index `example` to get `'hi'`. You use one key to get a second `dict` that you index with the other key. – chepner Oct 25 '22 at 14:58

1 Answers1

3

You could write a simple utility to handle list-valued keys:

example = {'a': {'b': 'hi'}, 'c': 1}
keys = ['c', ['a', 'b']]


def fetch_from_dict(dictionary, key):
    if isinstance(key, list):
        d = dictionary
        for k in key:
            d = d[k]
        return d
    else:
        return dictionary[key]


for key in keys:
    print(fetch_from_dict(example, key))

Result:

1
hi

Depending on your actual dictionary you might have to handle more special cases.

rdas
  • 20,604
  • 6
  • 33
  • 46