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

时间:2020-04-16 17:37:33

标签: python

真的是愚蠢而烦人的问题。我有这本字典:

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

我正在尝试检查targetMeanPrice是否在词典中。如果是,那么是否有值。然后打印该值。当我运行代码时,if语句将被忽略,而else条件中的print语句将被执行。我是否使事情复杂化了?

查看代码:

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

4 个答案:

答案 0 :(得分:1)

第一个条件应该是

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

更简洁地说

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

为了安全地实现该嵌套值,我想你想要

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

答案 1 :(得分:1)

您继续在实际上不想要这些值的字典上调用values。不要那样做! :)

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

或者不是在获得值之前进行测试,而只是使用默认值get

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

答案 2 :(得分:1)

您只需要检查一下即可:

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

似乎您的代码也无法正确制表:

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

答案 3 :(得分:1)

try语句在这里可以很好地工作。如果financialData中不存在GIS或GIS中不存在targetMeanPrice,则except子句中的代码由KeyError触发。

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