-1

I currently have a python function that goes through a json and returns the keys as a list of lists. For example, if a json was like

{'employee':{
     'info':{'name':'bob' , 'id':4 }, 
     'department':{'name':'sales' , 'floor':1}}} 

it would return a list like

[[['employee'], ['info'], ['name']],
 [['employee'], ['info'], ['id']],
 [['employee'], ['department'], ['name']],
 [['employee'], ['department'], ['floor']]] .

If I wanted to look up, for example, the employees name, is there a way I could reference the list to make its corresponding entry from a list of lists into something like

json['employee']['info']['name']?
Selcuk
  • 57,004
  • 12
  • 102
  • 110
lotad
  • 99
  • 1
  • 1
  • 5
  • 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) – bb1 Apr 01 '21 at 04:53

1 Answers1

1

I don't think there is a built-in method but you can use reduce creatively for this purpose:

>>> from functools import reduce
>>> d = {'employee': {'info': {'name': 'bob', 'id': 4}, 'department': {'name': 'sales', 'floor': 1}}}

then

>>> path =[['employee'], ['info'], ['name']]
>>> reduce(lambda sub_dict, key: sub_dict.get(key[0]), path, d)
'bob'

or

>>> path = [['employee'], ['department'], ['name']]
>>> reduce(lambda sub_dict, key: sub_dict.get(key[0]), path, d)
'sales'
Selcuk
  • 57,004
  • 12
  • 102
  • 110