Handling KeyError in conditional statement python when reading json file

keyerror python
python key error but key exists
python get value from dictionary if key exists
python check if key exists in list of dictionaries
python check for key error
raise keyerror(key) from none
python check if value in dictionary

So I am reading through two json files to check if the keys file name and file size exist. In one of the files i only have the key filename and not file size. When running my script it keeps through a KeyError , i would like to instead make it print out the file name/names that do not have the key file size.

The error i get is :

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

My code is as follows :

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

You can check if a key exists in dictionary by doing 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
>>>

Python KeyError Exceptions and How to Handle Them – Real Python, is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value. This code will take the name that you provide at the prompt and attempt to retrieve the age for that person. Whatever you type in at the prompt will be used as the key to the ages dictionary, on line 4.

The if key in dict approach is likely right for you, but it's worth also knowing about the get() method of dict objects.

You can use this to attempt to retrieve a key's value from the dictionary and if it's not present it'll return a default value instead - None by default or you can specify your own value:

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"

This can be convenient in some situations. You can also write this long hand as:

defalut_fname = data["file_name"] if "file_name" in data else "file not found" 

But I don't like having to write the key that many times!

Python KeyError Exceptions and How to handle them, exceptions. It is also useful where the get() and the if and in operators are not supported. Here, in this example there are two cases— normal case and a backup case. The way this works is by first having a json file on your disk. The program then loads the file for parsing, parses it and then you can use it. Related course: Complete Python Programming Course & Exercises. python read json JSON file. Create a file on your disk (name it: example.json). The python program below reads the json file and uses the

Use if 'File Size' not in data_current:

When using in against a dict, python looks at keys, not at the values.

How to check if a key exists in Json Object and get its value, How can I tell if a JSON key is available? Reading JSON from a File. On the other end, reading JSON data from a file is just as easy as writing it to a file. Using the same json package again, we can extract and parse the JSON string directly from a file object. In the following example, we do just that and then print out the data we got:

Python KeyError Exception Handling Examples, In this tutorial, you'll learn how to handle Python KeyError exceptions. A Python KeyError exception is what is raised when you try to access a key that isn't in a python ages.py Get age for: Michael Traceback (most recent call last): File If the KeyError is raised from a failed dictionary key lookup in your own code, you  You may also manage the Python keyError exception by using the get method of the dictionary. The get method of the dictionary is used to return the value for the key. If a key does not exist the default is returned. If you do not provide the default, it defaults to None.

Effective Python: 90 Specific Ways to Write Better Python, And learn how to handle exceptions in Python. These types of situations occur when the input is inappropriate or you try to open a file with a wrong Syntax Errors, also known as parsing errors, occur when the parser identifies an incorrect statement. area=(126,149,212,462), pages=1)If you want the output into JSON  Example 2: Python read JSON file. You can use json.load() method to read a file containing JSON object.. Suppose, you have a file named person.json which contains a JSON object.

Python Check if key exists in JSON and iterate the JSON array, Python KeyError is raised when we try to access a key from dict, which doesn't exist. It's one of Python Comments and Statements · 4. 1 Traceback (most recent call last): File We can handle the KeyError exception using the try-​except block. If the key is missing, None is returned. Python Excel to JSON Conversion. 1. What is Python KeyError Exception? Python KeyError is raised when we try to access a key from dict, which doesn't exist. It's one of the built-in