Search code examples
pythonlistdictionarykey

Bypass top level keys in python nested dictionary to extract low level keys


I have a complex nested dictionary. I want to extract all "symbol" keys. I have tried functions extracting all values, .get, converting to a list, tuples, and I know I could break it down piece by piece, but I would like to know what is the most efficient, least error prone way to parse this without calling the top level keys. Top level keys change so creating functions to account for those is not ideal and opens up the possibility for breaking the code, so entering symbol = map['2022-05-10:1']['303.0']['symbol'] is not what I want to have to do.


Solution

  • Do get all symbol values in your nested dictionary you can use next example (dct is your dictionary from the question):

    print([i["symbol"] for d in dct.values() for v in d.values() for i in v])
    

    Prints:

    ['QQQ_051622C300', 'QQQ_051622C301', 'QQQ_051622C302', 'QQQ_051622C303']
    

    EDIT: If there are missing symbols:

    print(
        [
            s
            for d in dct.values()
            for v in d.values()
            for i in v
            if (s := i.get("symbol"))
        ]
    )