How does collections.defaultdict work?

前端 未结 15 1988
离开以前
离开以前 2020-11-22 12:50

I\'ve read the examples in python docs, but still can\'t figure out what this method means. Can somebody help? Here are two examples from the python docs

>         


        
15条回答
  •  隐瞒了意图╮
    2020-11-22 13:15

    The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.

    import collections
    
    def default_factory():
        return 'default value'
    
    d = collections.defaultdict(default_factory, foo='bar')
    print 'd:', d
    print 'foo =>', d['foo']
    print 'bar =>', d['bar']
    

    This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.

    $ python collections_defaultdict.py
    
    d: defaultdict(, {'foo': 'bar'})
    foo => bar
    bar => default value
    

提交回复
热议问题