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

读取json文件时处理python条件语句中的KeyError,python,json,python-3.x,python-2.7,dictionary,Python,Json,Python 3.x,Python 2.7,Dictionary,因此,我正在阅读两个json文件,以检查密钥文件名和文件大小是否存在。在其中一个文件中,我只有密钥文件名,而没有文件大小。当运行脚本时,它会遇到一个keyrerror,我想让它打印出没有密钥文件大小的文件名 我得到的错误是: if data_current['File Size'] not in data_current: KeyError: 'File Size' file1.json {"File Name": "personDetails.json Exists", "File Si

因此,我正在阅读两个json文件,以检查密钥文件名和文件大小是否存在。在其中一个文件中,我只有密钥文件名,而没有文件大小。当运行脚本时,它会遇到一个keyrerror,我想让它打印出没有密钥文件大小的文件名

我得到的错误是:

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

如果“文件大小”不在数据中,请使用
。\u当前:

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

在中对dict使用
时,python会查看键,而不是值。

如果“文件大小”不在当前数据中,则可以通过执行
检查字典中是否存在键:

>>> 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
方法很可能适合您,但也值得了解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" 
但是我不喜欢把钥匙写那么多次