Python KeyError 的原因

Python cause of KeyError

我应该做什么,以避免在我的代码中出现 Keyerror,我是菜鸟 :) 我加载 json 并通过标记 status_name 打印数组中的所有值,但是算法在 Keyerror 上失败了,我该如何处理它然后将结果列表保存到一个文件?

import json
with open(r'.json', encoding='utf-8') as fp:
    data = json.load(fp)

for data in data:
    print(data['status_name'])

我根据请求从所有标签 status_name 获取数据,但是当请求到达没有标签 status_name 的标签时,我得到:

Traceback (most recent call last):
line 6, in <module>
KeyError: 'status_name'

Print Output:
v
v
v
m
u
u
m
v
v
v
v

我想打印 none 或跳过这些块

您的数据似乎没有名为 'status_name' 的键。先尝试仅打印数据,然后查看您要查找的内容的实际密钥是什么。

至于保存在文件中,可以用'w'方式打开文件,在循环结束时写入数据。像这样:

文件=打开(data.txt,'w')

对于数据中的 d:

打印(d['status_name'])

file.write(d)

我将 'data' 更改为 'd',因为它有点令人困惑。

不要忘记在循环后关闭文件。

错误处理有两种方式:

方法一

import json

with open(r'.json', encoding='utf-8') as fp:
    data = json.load(fp)

new_data = []
for d in data: # use different variable name
    # is d a dictionary and does it have 'status_name' as a key?
    if isinstance(d, dict) and 'status_name' in d:
        new_data.append(d)

"""    
# the above loop can be reduced to the more "Pythonic" list comprehension:
new_data = [d for d in data if isinstance(d, dict) and 'status_name' in d]
"""
with open('new_json', 'w', encoding='utf-8') as fp:
    json.dump(new_data, fp)

方法二

import json

with open('.json', encoding='utf-8') as fp:
    data = json.load(fp)

new_data = []
for d in data: # use different variable name
    # assume d is a dictionary with key 'status_name'
    try:
        value = d['status_name']
    except Exception:
        pass # don't append d
    else:
        new_data.append(d) # no exception so append d

with open('new_json', 'w', encoding='utf-8') as fp:
    json.dump(new_data, fp)
    
import xlwt
import json
with open(r'name.json', encoding='utf-8') as fp:
    data = json.load(fp)
channels = set() # unique data
for item in data['items']: 
    if 'status_name' in item: #checking if there is a tag, bypass Keyerror
        channels.add(item['status_name'])
        print(item['status_name'])
print(channels) # print unique data

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet Name")
# Writing on specified sheet
sheet.write(0, 0, 'Channels')
row = 1
for channel in sorted(channels):
    sheet.write(row, 0, channel)
    row += 1
workbook.save("name.xls")