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

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:

主站蜘蛛池模板: 永春县| 阿城市| 和硕县| 响水县| 藁城市| 汝阳县| 大化| 德庆县| 遵义县| 潼关县| 毕节市| 夏邑县| 博罗县| 龙游县| 始兴县| 新蔡县| 库尔勒市| 平遥县| 井研县| 宿迁市| 墨脱县| 颍上县| 威信县| 龙山县| 大厂| 沁水县| 论坛| 民权县| 汝阳县| 张家界市| 特克斯县| 东乡族自治县| 罗山县| 崇左市| 庄浪县| 平塘县| 高淳县| 榆林市| 通渭县| 邓州市| 昂仁县|