Python KeyError如果逻辑或尝试逻辑

Bit*_*iac 0 python dictionary python-3.x keyerror

我正在尝试循环一些JSON数据以导出到CSV并且一切顺利,直到我得到一些我需要获得某些字段值的数据,其中这些字段并不总是存在于"tags"下面.

我收到的错误是:

for alarm in tag["alarmst"]:
        KeyError: 'alarmst'
Run Code Online (Sandbox Code Playgroud)

我相信内置异常读取这意味着键/字段不存在.

我在错误和异常中读到,我可以将此逻辑放在try语句中,如果此键不存在,请不要给我错误并执行其他操作或转到"tag"下面的下一组记录中"alarmst"就是将该(以及指定的其他字段)转储到该文件中.

我无法弄清楚如何告诉这个逻辑停止给我这个错误,并且只使用csv_file.writerow()带有所有字段值的函数(如果只存在"alarmst").

由于我将在这个Python进程运行之前使用一个文件和进程将"devs"和"tags"添加到他们自己的CSV文件中,我无法解析数据并减少for循环中的for循环.

我不确定这个问题if tag["alarmst"] in tag:是否是由于其他人中存在如此多的for循环,或者我是否需要以某种方式使用try语句,或者如果我因为我是新的而没有正确地做其他事情在这个级别的编码Python,但它似乎适用于迄今为止的需要.

我在Windows 10操作系统上运行它,如果这有任何区别,但我认为它没有.

启动代码:

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            for alarm in tag["alarmst"]:
                csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
Run Code Online (Sandbox Code Playgroud)

如果代码:

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            for alarm in tag["alarmst"]:
                if tag["alarmst"] in tag:
                    csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])
Run Code Online (Sandbox Code Playgroud)

Ale*_*all 6

tag["alarmst"]是什么引发了错误.它意味着获取tag与密钥相关联的值,"alarmst"并且没有这样的密钥,因此它失败了.if tag["alarmst"] in tag会抛出相同的错误,而且如果它低于此值,你甚至不会达到这一点for alarm in tag["alarmst"]:.你想要的是:

if "alarmst" in tag:
    for alarm in tag["alarmst"]:
Run Code Online (Sandbox Code Playgroud)

但更好的是:

for alarm in tag.get("alarmst", []):
Run Code Online (Sandbox Code Playgroud)

get类似于通常的方括号访问,但如果找不到键,则第二个参数是默认值.因此,如果"alarmst"不在字典中,这将基本上是:

for alarm in []:
Run Code Online (Sandbox Code Playgroud)

这只是一个根本不会运行的空循环.