python 调用for循环时出现键错误[重复]

mfuanj7w  于 2023-03-07  发布在  Python
关注(0)|答案(1)|浏览(115)
    • 此问题在此处已有答案**:

How do I avoid KeyError when working with dictionaries?(3个答案)
4天前关闭。
当我试图在json中循环遍历项目时,其中一些不包含我所调用的元素,我得到了关键错误。

for i in range(200000): #(amount of lines in file):
 data["tasks"][i]["Assignments"] = [data["tasks"][i]["Assignments"][0]]
    
KeyError: 'Assignments'

如何避免此错误?

z4bn682m

z4bn682m1#

就像注解中提到的那样使用try/except

for i in range(200000): #(amount of lines in file):
    try:
        data["tasks"][i]["Assignments"] = [data["tasks"][i]["Assignments"][0]]
    # if KeyError occurs, just skip the line
    except KeyError:
        continue

相关问题