Python-如果在JSON中找不到元素,则将值更新为0

时间:2020-09-16 04:17:18

标签: python python-3.x dataframe

我有一个读取JSON文件结构并提取Off_peak,Peak和Shoulder价格的代码。 有一些所有元素都存在的JSON,而有些元素只有Peak和Off_Peak而没有肩膀。

try:
    for check in data[0]['planData']['contract'][0]['tariffPeriod'][0]['touBlock']:
        if "Off" in check['name']:
            Off_Peak = check['blockRate'][0]['unitPrice']
        elif "Peak" in check['name']:
            Peak = check['blockRate'][0]['unitPrice']
        elif "Shoulder" in check['name']:
            Shoulder = check['blockRate'][0]['unitPrice']
        
except:
    Off_Peak = ""
    Peak = ""
    Shoulder = ""

我的代码使用所有这些元素(甚至是否找到)检查并更新变量。但是,如果仅找到2个元素,则不会更新未找到的元素,而我想将其更新为0。API示例

API - https://api.energymadeeasy.gov.au/plans/dpids/AMA62448MBE1?postcode=4000

例如,有一个文件具有Off_Peak和Peak,但肩膀变量保持空白,但如果找不到,我想将其更新为0。我尝试使用下面的代码,但无法正常工作。

for check in data[0]['planData']['contract'][0]['tariffPeriod'][0]['touBlock']:
    if "Off" in check['description']:
        Off_Peak = check['blockRate'][0]['unitPrice']
        print('Off_Peak',Off_Peak)
    elif "Peak" in check['description']:
        Peak = check['blockRate'][0]['unitPrice']
        print('Peak',Peak)
    elif "Shoulder" in check['description']:
        Shoulder = check['blockRate'][0]['unitPrice']
        print('Shoulder',Shoulder)
    elif Off_Peak==None:
        Off_Peak=0
    elif Peak==None:
        Peak=0
    elif Shoulder==None:
        Shoulder=0

预期产量

Plan_ID Post_Code   Plan_Type   Plan_Name   Retailer_Name   Retailer_Code   Distributor_Name    State   Effective_Date  Solar_Rate  Discount_Type   Discount    Daily_Rate  CL1 CL2 Single_Rate Off_Peak    Peak    Shoulder
AMA62448MBE1    4000    TOU amaysim Post-paid Electricity - Business    amaysim Energy  AMA Energex QLD 1/07/2020   8           136.8               21.9648 23.328  0

2 个答案:

答案 0 :(得分:1)

我认为不必为此复杂化,只需将所有3个初始值设置为0。如果找到该值,请再次设置它,否则它将保持为0-

Off_Peak = 0
Peak = 0
Shoulder = 0
try:
    for check in data[0]['planData']['contract'][0]['tariffPeriod'][0]['touBlock']:
        if "Off" in check['name']:
            Off_Peak = check['blockRate'][0]['unitPrice']
        elif "Peak" in check['name']:
            Peak = check['blockRate'][0]['unitPrice']
        elif "Shoulder" in check['name']:
            Shoulder = check['blockRate'][0]['unitPrice']        
except:
    # No need to set it again, but not removing it
    Off_Peak = 0
    Peak = 0
    Shoulder = 0

答案 1 :(得分:-1)

如何使用“三进制条件”表示一行,如果不是这样的话。

即,如果找到,则将数据输入变量,否则输入0

这样使用

test = True if 10+10 == 20 else False

for check in data[0]['planData']['contract'][0]['tariffPeriod'][0]['touBlock']:
    Off_Peak = check['blockRate'][0]['unitPrice'] if "Off" in check['name'] else 0 
    Peak = check['blockRate'][0]['unitPrice'] if "Peak" in check['name'] else 0 
    Shoulder = check['blockRate'][0]['unitPrice'] if "Shoulder" in check['name'] else 0 

编辑:

我刚刚看到了您的API,并且还没有对其进行任何测试!