Python's dictionaries generally look up keys directly, such as
dict={'a':1,'b':2,'c':3} print(dict['a'])
But if the key you are looking for doesn't exist, it will report: KeyError.
For example, if you want to see print(dict['d'])
Since there is no key in the dict at this time, it will report an error directly, so this time in fact python gives us a great solution, that is to use the
setdefault, used as follows: (key,[set what you want the value to be if it doesn't exist, defaults to None])
So here's how we can solve it with this method:
print(('d',0))
Then there is no problem, note that is setdefault is if you want to add a new value to the dict on the use of this function, if you simply want to do a lookup, encountered the key does not exist or want to read through the value of the key can be a default value, then it is recommended to use defaultdict
First of all introduce the so-called defaultdict, from the Collections module, Collections is a collection module, defaultdict (function_factory) builds a dictionary-like object, where the value of the key, to determine the value of the assignment, but the type of the value is an instance of the function_factory class and has a default value. value type is function_factory class instance, and has a default value. Another concept introduced here is that of factory functions. Python's factory functions are those built-in functions that are class objects, and when you call them, you're actually creating a class instance.
For example, int(), str(), set(), etc. Here we look at examples:
import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = (list) for k, v in s: d[k].append(v) print(d['yellow']) print(d['white']) print(list(()))
We end up with the following output:
We can see that when there is no corresponding key in d, the final return is an empty list, that is because we set the defaultdict when the factory function is list, and the default value of list is an empty list, the following we look at if the factory function is set() what will be the case
import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = (set) for k, v in s: d[k].add(v) print(d['yellow']) print(d['white']) print(list(()))
The resultant output is as follows:
Addendum: python reporting error with KeyError: 'longitude'
python reports an error with KeyError: 'longitude'
The error reporting screen is shown below:
I searched the internet for ways to do this and did find a solution: one that might work for youSolution 1
But I tried it and it still didn't work, so when I fixed my eyes on it, I realized that it was again due to my carelessness. Ah, as you can see below, there's a missing comma in front of longitude.
Below:
So that's the problem solved. Okay, I'll get back to my course design.
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.