简体   繁体   中英

How do you check to see if a value exists in a dictionary within a dictionary?

Really dumb and annoying question. I have this dictionary:

{
    'GIS': {
        'maxAge': 86400,
        'currentPrice': 60.3,
        'targetHighPrice': 67.0,
        'targetLowPrice': 45.0,
    }
}

I am trying to check if the targetMeanPrice is in the dictionary. If it is, is there a value. Then print the value. When I run my code the if statement gets ignored and the print statement in the else condition gets executed. Am I overcomplicating things?

see code:

if 'targetMeanPrice' in financialData['GIS'].values():
    print("hi")
    if(financialData.isnull(financialData['targetMeanPrice'].values)): # if the value of the target mean is not equal to null
        target = float(financialData['targetMeanPrice'].values)

    print("this is the targetMeanPrice:",target)) 

else:
      print("No targetMeanPrice here")

That first condition should be

if 'targetMeanPrice' in financialData['GIS'].keys():

which more succinctly is just

if 'targetMeanPrice' in financialData['GIS']:

To reach that nested value safely, I think you want

target = financialData.get('GIS', {}).get('targetMeanPrice', None)
if target:
    # found it
else:
    # didn't find it

You keep calling values on dictionaries where you don't actually want the values yet. Don't do that: :)

if 'targetMeanPrice' in financialData['GIS']:
    target = financialData['GIS']['targetMeanPrice']
    print("this is the targetMeanPrice:", target) 
else:
    print("No targetMeanPrice here")

Or rather than testing before you get the value, just get with a default:

target = financialData['GIS'].get('targetMeanPrice', None)
if target is not None:
    print("this is the targetMeanPrice:", target) 
else:
    print("No targetMeanPrice here")

you want to just check it do it like this:

if 'targetMeanPrice' in financialData['GIS']:

also it seems that your code is not well tabed:

if (financialData.isnull(financialData['targetMeanPrice'].values)):
    target = float(financialData['targetMeanPrice'].values)
    print("this is the targetMeanPrice:", target)) 

A try statement would work well here. If GIS doesn't exist in financialData or targetMeanPrice doesn't exist in GIS, the code in the except clause is triggered by the KeyError .

try:
    target = financialData[“GIS”][“targetMeanPrice”]
    print("this is the targetMeanPrice:", target)
except KeyError:
    print("No targetMeanPrice here")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM