If you didn't assign default data type, then the defaultdict will not generate a default value for a missing key. For this case, we can use get(key) to find the key value and it will not cause error if the key is missing. See the following example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#defaultdict will not always generate default value | |
#if you didn't assign default data type to it, using defaultdict[key] to find the key might get an error | |
#defaultdict has default data type | |
>>> x = defaultdict(int) | |
>>> x | |
defaultdict(<type 'int'>, {}) | |
>>> x["abc"] | |
0 | |
>>> x | |
defaultdict(<type 'int'>, {'abc': 0}) | |
#defaultdict has no default data type | |
>>> x = defaultdict() | |
>>> x | |
defaultdict(None, {}) | |
>>> x["abc"] | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
KeyError: 'abc' | |
#for safety, instead, we can use get() to find the key | |
>>> x.get("abc") #will return nothing, but will not cause error | |
>>> |
No comments:
Post a Comment