Python KeyError: Checking  The Python Dict Keys

0

Python KeyError: Checking  The Python Dict Keys (Done)

Python’s KeyError exception is a common exception encountered by beginners. Knowing why a KeyError can be raised and some solutions to prevent it from stopping your program are essential steps to improving as a Python programmer.

This program doesn’t work:

Run it, and it blows up on you:

In general, there are three ways to solve this problem. The first is the “key in the dict” idiom:



The output:

Now imagine that you can not change the description (). Another code could be based on your original behavior, and you do not want to repeat everything.

Alternatively, you can import it from the library. Therefore, the comparison function () can not be changed.

You can fix the program by recording the KeyError:

The same conclusion. Use try / except KeyError if you do not have direct access to the dictionary in your password, or direct access causes a number of problems.

However, let us concentrate on direct work with dict because it is often possible. This leads us to the third approach: the dict.get () method.

This regains the value if the key exists or an alternative value (if not) without exception. You can call it with two arguments: a key and a default value:

You can also call it with an argument, so the default is None

You can use this function:

Then the display element (“Kr”) prints “The correct Kr number is 36” and the presentation element (“Rn”) returns “Ordinal Rn is unknown.

Can we use it in the description ()? Yes, but it is more complicated than it seems because unlike the showelement (), the output format is completely different if the key does not exist. Here is the focus:

It works … in general. The idea is to rely on the default value to indicate if a key is missing. But what happens if the key is present and its value is the default setting?

After all, no one can be a value in a dictionary. Even if we think it’s not in this dictionary, what happens if an error occurs? The previous code can cover this bug and hide it in your program just like mine.

We need a watch from the team. In other words, something that could not cost the DIT. It is better to create a separate object, literally, an instance of the object and pass it on to the default .get () value:

The value of the key can not be missing because it believes it is missing immediately before searching the dictionary. If it is missing, we know for certain that it does not exist in the dictionary.

These three approaches: “key in dict”, “try / exclude KeyError” and “dict.get ()” – have many advantages. Work so well that you know how to use the best in different situations.

If your program has several subprocesses, you should consider other surprises.

Video on Python KeyError

Leave A Reply

Your email address will not be published.