读取json文件时处理条件语句python中的KeyError

时间:2018-11-30 09:14:56

标签: python json python-3.x python-2.7 dictionary

因此,我正在阅读两个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")

3 个答案:

答案 0 :(得分:1)

您可以通过执行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
>>>

答案 1 :(得分:1)

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" 

但是我不喜欢多次写密钥!

答案 2 :(得分:0)

使用if 'File Size' not in data_current:

针对字典使用in时,python会查看键,而不是值。