Defaultdict underlying code
When searching for a value in a dictionary, if the key does not exist then it will return a KeyError error instead of a default value, this time you can use the defaultdict function.
Attention:When using dict[key]=value, an error is reported if the key does not exist; when using (key), a default value is returned if the key does not exist.
defaultdict accepts a factory function as an argument, constructed as follows:
dict =defaultdict( factory_function)
factory_function can be list, set, str, etc. The function is to return the default value of the factory function when the key does not exist, for example, list corresponds to [ ], str corresponds to the empty string, set corresponds to set( ), and int corresponds to zero.
defaultdict is a word class of python's built-in dict class, with the same functionality as dict, but it comes with a default value that is returned if the key value does not exist.
Sample code:
lst = ['A', 'B', 'C', 'D', 'e'] dic = {} for i in lst: dic[i] += 1 print(dic)
If you access a dictionary with a non-existent key value, you will get a KeyError error, which can be avoided by using the defaultdict class.
() method: there are two arguments, the first is the parameter and the second is the default value.
Sample code:
lst = ['A', 'B', 'C', 'D', 'e'] dic = {} for i in lst: (i, 0) dic[i] += 1 print(dic)
Sample code:
from collections import defaultdict dict1 = defaultdict(int) dict2 = defaultdict(set) dict3 = defaultdict(str) dict4 = defaultdict(list) dict4[1] = 666 print(dict1[0]) print(dict2[0]) print(dict3[0]) print(dict4[0]) print(dict4[1])
Running effects:
Does Python's dictionary have a default value
It is well known that in Python if you access a key that doesn't exist in a dictionary, a KeyError exception is thrown (JavaScript returns undefined if a property doesn't exist in an object). But sometimes it is very convenient to have default values for each key in the dictionary. Take for example the following example:
strings = ('puppy', 'kitten', 'puppy', 'puppy', 'weasel', 'puppy', 'kitten', 'puppy') counts = {} for kw in strings: counts[kw] += 1
This example counts the occurrences of a word in strings and records them in the counts dictionary. For each occurrence of the word, the number of the value stored in the key corresponding to counts is increased by 1. But in fact, running this code throws a KeyError exception, which occurs when each word is counted for the first time, because there is no such thing as a default value in Python's dicts.
In order to solve the above problem, we can first add a judgment statement, if the key does not exist, then its value value is set to 1
strings = ('puppy', 'kitten', 'puppy', 'puppy', 'weasel', 'puppy', 'kitten', 'puppy') counts = {} for kw in strings: if kw not in counts: counts[kw] = 1 else: counts[kw] += 1
The default value can also be set using the setdefault method:
strings = ('puppy', 'kitten', 'puppy', 'puppy', 'weasel', 'puppy', 'kitten', 'puppy') counts = {} for kw in strings: (kw, 0) counts[kw] += 1
There is another way to perform initialization operations on dictionaries - defaultdict
The defaultdict class is like a dict, but it is initialized using a type:
>> from collections import defaultdict >>> d = defaultdict(list) >>> d['k1'] [] >>> d defaultdict(<class 'list'>, {'k1': []}) >>> d['k2']='kobe' >>> d defaultdict(<class 'list'>, {'k1': [], 'k2': 'kobe'}) >>> d['k3'].append('lebron') >>> d defaultdict(<class 'list'>, {'k1': [], 'k2': 'kobe', 'k3': ['lebron']})
to this article on the use of Python defaultdict method to analyze the article is introduced to this, more related Python defaultdict content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!