user16950345
user16950345

Reputation:

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.

Upvotes: 1

Views: 778

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195653

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"))
    ]
)

Upvotes: 1

Freddy Mcloughlan
Freddy Mcloughlan

Reputation: 4506

If this structure is consitent, you can use:

# x is your dictionary

symbols = []

for date in x.values():
    for i in date.values():
        for j in i:
            if "symbol" in j:
                symbols.append(j["symbol"])
>>> symbols
['QQQ_051622C300',
 'QQQ_051622C301',
 'QQQ_051622C302',
 'QQQ_051622C303']

Or just remove symbols = [] and replace symbols.append(j["symbol"]) with print(j["symbol"]) if you would rather just print the symbol key instead of saving it.

Upvotes: 1

Related Questions