Home > OS >  Bypass top level keys in python nested dictionary to extract low level keys
Bypass top level keys in python nested dictionary to extract low level keys

Time:05-16

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.

    {'2022-05-16:1': {'300.0': [{'putCall': 'CALL',
    'symbol': 'QQQ_051622C300',
    'description': 'QQQ May 16 2022 300 Call',
    'exchangeName': 'OPR',
    'bid': 3.77,
    'ask': 3.94,
    'last': 3.86,
    'mark': 3.86,
    'bidSize': 78,
    'askSize': 34,
    'bidAskSize': '78X34',
    'lastSize': 0,
    'highPrice': 5.38,
    'lowPrice': 2.17,
    'openPrice': 0.0,
    'closePrice': 4.19,
    'totalVolume': 23707,
    'tradeDate': None,
    'tradeTimeInLong': 1652472847483,
    'quoteTimeInLong': 1652472899026,
    'netChange': -0.33,
    'volatility': 26.028,
    'delta': 0.602,
    'gamma': 0.049,
    'theta': -0.411,
    'vega': 0.117,
    'rho': 0.017,
    'openInterest': 5828,
    'timeValue': 1.92,
    'theoreticalOptionValue': 4.19,
    'theoreticalVolatility': 29.0,
    'optionDeliverablesList': None,
    'strikePrice': 300.0,
    'nonStandard': False}],
  '301.0': [{'putCall': 'CALL',
    'symbol': 'QQQ_051622C301',
    'description': 'QQQ May 16 2022 301 Call',
    'exchangeName': 'OPR',
    'bid': 3.23,
    'ask': 3.35,
    'last': 3.27,
    'mark': 3.29,
...

CodePudding user response:

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.

CodePudding user response:

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