I'll forget it soon, so make a note.
When retrieving a value from a dict instance with a key
If you think about it, it is good to use the get method.
>>> d = {"a": 1, "b": 2}
>>> d["c"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> d.get("c") #Returns None if default is not specified
>>> d.get("c", 3) #If default is specified, that value will be returned.
3
>>>
The nice thing is that you can specify get (key [, default]) and the default value.
So you can easily write anything like the following with get.
>>> c = d["c"] if "c" in d else 3
>>> c
3
>>> c = d["c"] if d.has_key("c") else 3
>>> c
3
#The above guys can write neatly with the default specification of get
>>> c = d.get("c", 3)
>>> c
3
In addition, the following processing, which was imported defaultdict in order to write neatly, can also be written with get.
However, it is better to use defaultdict, so if you want to improve readability, you should use defaultdict.
>>> from collections import defaultdict
>>> dd = defaultdict(int, d)
>>> dd
defaultdict(<type 'int'>, {'a': 1, 'b': 2})
>>> dd["c"] += 1 #To a key that does not exist+=No error occurs even if 1 is set, and the default value 0 of int is implicitly set.
>>> dd["c"]
1
#You can write without using defaultdict by using get
>>> d
{'a': 1, 'b': 2}
>>> d["c"] = d.get("c", 0) + 1 #Get the default value 0 from a non-existent key+1 do
>>> d["c"]
1
Recommended Posts