0

I have a function that should use the value of the key that we pass as argument. The key would lookup the value in a nested dictionary. Ex:

nested_dict = ... # dump from json a very nested dictionary

def get_value(nested_dict, composed_key):
    # ? nested_dict[composed_key]

Is there a way to do this :

get_value(nested_dict, ["level1"]["level2"]...["leveln"])

Or :

get_value(nested_dict, "level1.level2...leveln")

?

How can I do?

Thanks

Farah
  • 2,469
  • 5
  • 31
  • 52

1 Answers1

0

You can pass a list of the keys as second argument like this:

def get_value(nested_dict, composed_key):
  for x in composed_key:
    print(nested_dict[x])

And call like:

get_value(nested_dict, ["level1","level2",...,"leveln"])
Wasif
  • 14,755
  • 3
  • 14
  • 34