【问题标题】:Handling KeyError in conditional statement python when reading json file读取json文件时处理条件语句python中的KeyError
【发布时间】:2023-03-22 14:37:01
【问题描述】:

所以我正在阅读两个 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")

【问题讨论】:

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


    【解决方案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
    >>>
    

    【讨论】:

      【解决方案2】:

      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" 
      

      但我不喜欢多次写密钥!

      【讨论】:

        【解决方案3】:

        使用if 'File Size' not in data_current:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-18
          • 1970-01-01
          相关资源
          最近更新 更多