Skip to content Skip to sidebar Skip to footer

Find All The Keys And Keys Of The Keys In A Nested Dictionary

I'm trying to find all the attributes of the data in a nested dictionary in Python. Some objects may have multiple levels in their key definition. How can I find the header of such

Solution 1:

You'll need to traverse the nested dicts, your current approach only gets as far as the keys of the root dictionary.

You can use the following generator function to find the keys and traverse nested dicts recursively:

import json 
from pprint import pprint

deffind_keys(dct):
    for k, v in dct.items():
        ifisinstance(v, dict):
            # traverse nested dictfor x in find_keys(v):
                yield"{}_{}".format(k, x)
        else:
            yield k

Given a list of dictionaries as derived from your json object, you can find the keys in each dict and put them in a set so entries are unique:

s = set()
for d in json.loads(lst):
    s.update(find_keys(d))

pprint(s)

set(['Event_Code_Code',
     'Event_Description',
     'Event_ExpirationDate',
     'Event_Id',
     'Event_ItemId_Id',
     'Event_Quantity',
     'Event_RefInfo_SentUtc',
     'Event_RefInfo_Source',
     'Event_RefInfo_TId_Id',
     'Event_RefInfo_UserId_Id',
     'Event_Sku_Sku',
     'MessageType'])

Post a Comment for "Find All The Keys And Keys Of The Keys In A Nested Dictionary"