简体   繁体   English

您如何检查字典中的字典中是否存在值?

[英]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.我正在尝试检查 targetMeanPrice 是否在字典中。 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.当我运行我的代码时,if 语句被忽略,而 else 条件中的 print 语句被执行。 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.您一直在实际上并不需要这些值的字典上调用values 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:或者,不要在get值之前进行测试,而是使用默认值:

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. try语句在这里可以很好地工作。 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 .如果金融数据中不存在 GIS 或 GIS 中不存在 targetMeanPrice ,则except子句中的代码由KeyError触发。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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