官术网_书友最值得收藏!

defaultdict

The defaultdict object is a subclass of dict and therefore they share methods and operations. It acts as a convenient way to initialize dictionaries. With a dict, Python will throw a KeyError when attempting to access a key that is not already in the dictionary. The defaultdict overrides one method, __missing__(key), and creates a new instance variable, default_factory. With defaultdict, rather than throw an error, it will run the function, supplied as the default_factory argument, which will generate a value. A simple use of defaultdict is to set default_factory to int and use it to quickly tally the counts of items in the dictionary, for example:

You will notice that if we tried to do this with an ordinary dictionary, we would get a key error when we tried to add the first key. The int we supplied as an argument to default dict is really the function int() that simply returns a zero. We can, of course, create a function that will determine the dictionary's values. For example, the following function returns True if the supplied argument is a primary color, that is red, green, or blue, or returns False otherwise:

def isprimary(c):  
if (c == 'red') or (c == 'blue') or (c == 'green'):
return True
else:
return False

We can now create a new defaultdict object and use the isprimary function to populate it:

主站蜘蛛池模板: 卢湾区| 永靖县| 南宁市| 体育| 武安市| 兴安盟| 枣庄市| 宜君县| 女性| 曲阜市| 平邑县| 乡城县| 宜昌市| 贵港市| 金沙县| 卓尼县| 徐州市| 中西区| 浦北县| 乾安县| 翼城县| 庆阳市| 涪陵区| 南乐县| 乳源| 枣强县| 秭归县| 宜川县| 林西县| 泰和县| 邮箱| 岑溪市| 芮城县| 安溪县| 西畴县| 通化县| 黎城县| 乌审旗| 翁牛特旗| 嘉善县| 保定市|