[英]Handling KeyError in conditional statement python when reading json file
所以我正在阅读两个json文件来检查密钥文件名和文件大小是否存在。 在其中一个文件中,我只有密钥文件名而不是文件大小。 当我运行我的脚本时,它会通过KeyError,我想改为打印出没有密钥文件大小的文件名/名称。
我得到的错误是:
if data_current['File Size'] not in data_current:
KeyError: 'File Size'
file1.json
{"File Name": "personDetails.json Exists", "File Size": "7484"}
{"File Name": "agent.json Not Exists"}
file2.json
{"File Name": "personDetails.json Exists", "File Size": "7484"}
{"File Name": "agent.json Not Exists", "File Size": "9484"}
我的代码如下:
with open('file1.json', 'r') as f, open('file2.json', 'r') as g:
for cd, pd in zip(f, g):
data_current = json.loads(cd)
data_previous = json.loads(pd)
if data_current['File Size'] not in data_current:
data_current['File Size'] = 0
if data_current['File Name'] != data_previous['File Name']: # If file names do not match
print " File names do not match"
elif data_current['File Name'] == data_previous['File Name']: # If file names match
print " File names match"
elif data_current['File Size'] == data_previous['File Size']: # If file sizes match
print "File sizes match"
elif data_current['File Size'] != data_previous['File Size']: #
print "File size is missing"
else:
print ("Everything is fine")
if 'File Size' not in data_current:
您可以检查字典中是否存在键if 'File Size' not in data_current:
>>> data = {"File Size": 200} # Dictionary of one value with key "File Size"
>>> "File Size" in data # Check if key "File Size" exists in dictionary
True
>>> "File Name" in data # Check if key "File Name" exists in dictionary
False
>>>
if key in dict
方法中的if key in dict
可能适合您,但值得了解dict对象的get()
方法。
您可以使用它来尝试从字典中检索键的值,如果它不存在,它将返回默认值 - 默认情况下为None
,或者您可以指定自己的值:
data = {"foo": "bar"}
fname= data.get("file_name") # fname will be None
default_fname = data.get("file_name", "file not found") # default_fname will be "file not found"
在某些情况下这很方便。 你也可以写这个长手:
defalut_fname = data["file_name"] if "file_name" in data else "file not found"
但我不喜欢多次写密钥!
if 'File Size' not in data_current:
in
对dict使用in
,python会查看键,而不是值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.