defaultdict
  • a new dictionary-like object
  • overrides one method and adds one writable instance variable
  • the remaining functionality is the same as for the dict class
  • the type of the value for each key can be specified
  • Initialization
    # default_factory=None, defaultdict has the same performance as dict
    import collections
    
    def default_factory():
        return 'default value'
    
    d = collections.defaultdict()
    
    d['blue'] = 20 # defaultdict(None, {'blue': 20})
    
    # print(d['red']) # key doesn't exist, raise KeyError
                
    # default_factory=func_missing, if key does not exist, insert key with default value
    import collections
    
    def func_missing():
        return 0
    
    d = collections.defaultdict(default_factory = func_missing)
    
    d['blue'] = 20 # defaultdict(<function func_missing at 0x108af04a0>, {'blue': 20})
    
    print(d['red']) # key doesn't exist, insert key with default value
    # defaultdict(<function func_missing at 0x108af04a0>, {'blue': 20, 'red': 0})
                
    # list
    from collections import defaultdict
    
    s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
    d_list = defaultdict(list) # each value is a list
    for k, v in s:
        # access key which does not exist
        # insert key with an empty list
        # append value to list
        d_list[k].append(v)
    
    print(d_list) # defaultdict(list, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
                
    # dict
    from collections import defaultdict
    
    s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
    d_dict = defaultdict(dict) # each value is a list
    for k, v in s:
        # access key which does not exist
        # insert key with an empty dict
        # add key/value to dict
        d_dict[k][v] = 0
        
    print(d_dict) # defaultdict(, {'yellow': {1: 0, 3: 0}, 'blue': {2: 0, 4: 0}, 'red': {1: 0}})
                
    Methods
    # list
    list(d_list.keys()) # ['yellow', 'blue', 'red']
    list(d_list.values()) # [[1, 3], [2, 4], [1]]
    list(d_list.items()) # [('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])]
                
    # dict
    list(d_dict.keys()) # ['yellow', 'blue', 'red']
    list(d_dict.values()) # [{1: 0, 3: 0}, {2: 0, 4: 0}, {1: 0}]
    list(d_dict.items()) # [('yellow', {1: 0, 3: 0}), ('blue', {2: 0, 4: 0}), ('red', {1: 0})]
                
    Built-in Functions
    # list
    # convert to dict
    dict(d_list) # {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}
                
    # dict
    # convert to dict
    dict(d_dict) # {'yellow': {1: 0, 3: 0}, 'blue': {2: 0, 4: 0}, 'red': {1: 0}}
                
    Reference
  • Python 3 Standard Library
  • PyMOTW-3