Solve the problem of finding keyerror in Python dictionary

Time:2021-12-1

Python dictionaries generally look up keys directly, such as

?
1
2
dict={'a':1,'b':2,'c':3}
print(dict['a'])

However, if the searched key does not exist, it will report: keyerror:

For example, you want to check print (dict [‘d ‘])

Because there is no key in dict at this time, it will directly report an error. In fact, python provides us with a great solution at this time, that is, using

SetDefault, the usage is as follows: dict.setdefault (key, [set here if it doesn’t exist, the default is none])

Solve the problem of finding keyerror in Python dictionary

Here we can use this method:

?
1
print(dict.setdefault('d',0))

Then there’s no problem. Note that setDefault is used when you want to add a new value to dict. If you just want to do a search and encounter that the key does not exist or want to get a default value when reading the value through this key, it is recommended to use defaultdict

First, let’s introduce the so-called defaultdict, which comes from the collections module. Collections is a collection module. Defaultdict (function_factory) constructs an object similar to a dictionary, in which the value of the key is assigned by itself, but the type of value is function_ Factory class instances have default values. A concept is also introduced here, that is, factory functions. Python factory functions refer to those built-in functions that are class objects. When you call them, you actually create a class instance.

For example, int(), str(), set(), etc. Here we look at the following example:

?
1
2
3
4
5
6
7
8
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
    d[k].append(v)
print(d['yellow'])
print(d['white'])
print(list(d.items()))

The final output results are as follows:

Solve the problem of finding keyerror in Python dictionary

We can see that when there is no corresponding key in D, the last returned is an empty list. That’s because the factory function we used when setting defaultdict is list, and the default value of list is an empty list. Let’s see what it would look like if the factory function is set()

?
1
2
3
4
5
6
7
8
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(set)
for k, v in s:
    d[k].add(v)
print(d['yellow'])
print(d['white'])
print(list(d.items()))

The result output is as follows:

Solve the problem of finding keyerror in Python dictionary

Supplement: Python reports an error. Keyerror: ‘longitude’

Python reports an error with keyerror: ‘longitude’

The error reporting interface is shown in the figure below:

Solve the problem of finding keyerror in Python dictionary

I found a way on the Internet and did find a solution: what might be useful to you

But I tried and it was useless. So when I looked at it, I found that it was caused by my carelessness. Ah, as shown below, a comma is missing in front of longitude,

As shown below:

Solve the problem of finding keyerror in Python dictionary

So this problem is solved. OK, I’ll continue my course design.

The above is my personal experience. I hope I can give you a reference, and I hope you can support developepper.

Recommended Today

Datawhale pandas punch in – Chapter 4 grouping

Today, I’m learning Chapter 4 – grouping, which I think is a very important and useful knowledge of pandas. This chapter mainly introduces the application of AGG, transform, apply and other functions based on the growpy function.The textbook summarizes the three operations of grouping: aggregation, transformation and filtering. 1. Polymerization: The groupby object has defined […]