简体   繁体   English

KeyError的Python原因

[英]Python cause of KeyError

What I should to do, to avoid Keyerror in my code, I'm a noob :) I load json and print all the values ​​from the array by tag status_name , but the algorithm fails on an Keyerror , how can I handle it and then save the resulting list to a file?我应该怎么做,为了避免我的代码出现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'])

I get data from all tags status_name on request, but when the request reaches a tag where is no tag status_name , I get:我根据请求从所有标签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

I want to print none or skip such blocks我想不打印或跳过这些块

It seems like your data has no key named 'status_name'.您的数据似乎没有名为“status_name”的键。 Try printing only the data first, and see what is the actual key for what you're looking for.首先尝试仅打印数据,然后查看您要查找的内容的实际密钥是什么。

As for saving it in a file, you can open a file with the 'w' mode, and write the data at the end of the loop.至于保存在文件中,可以用'w'模式打开一个文件,在循环结束时写入数据。 Like this:像这样:

file = open(data.txt, 'w')文件 = 打开(数据.txt,'w')

for d in data:对于数据中的 d:

print(d['status_name'])打印(d['status_name'])

file.write(d) file.write(d)

I changed 'data' for 'd' cause it was a bit confusing.我将“数据”更改为“d”,因为这有点令人困惑。

And don't forget to close the file after the loop.并且不要忘记在循环后关闭文件。

There are two ways of handling the error:有两种处理错误的方法:

Method 1方法一

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)

Method 2方法二

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

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

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