- Python Data Structures and Algorithms
- Benjamin Baka
- 228字
- 2021-07-09 19:45:05
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:

- VMware View Security Essentials
- Git Version Control Cookbook
- Visual FoxPro程序設計教程(第3版)
- 新一代通用視頻編碼H.266/VVC:原理、標準與實現
- Python語言程序設計
- AngularJS Web Application Development Blueprints
- Getting Started with CreateJS
- Raspberry Pi for Secret Agents(Third Edition)
- x86匯編語言:從實模式到保護模式(第2版)
- aelf區塊鏈應用架構指南
- Python項目實戰從入門到精通
- Java并發編程:核心方法與框架
- Apache Solr PHP Integration
- Mastering XenApp?
- Building Scalable Apps with Redis and Node.js