How does collections.defaultdict work?

前端 未结 15 1992
离开以前
离开以前 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:16

    My own 2¢: you can also subclass defaultdict:

    class MyDict(defaultdict):
        def __missing__(self, key):
            value = [None, None]
            self[key] = value
            return value
    

    This could come in handy for very complex cases.

    0 讨论(0)
  • 2020-11-22 13:22

    There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/

    Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.

    In normal dictionaries, if in your example I try calling d[a], I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.

    0 讨论(0)
  • 2020-11-22 13:23

    defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.

    For example:

    somedict = {}
    print(somedict[3]) # KeyError
    
    someddict = defaultdict(int)
    print(someddict[3]) # print int(), thus 0
    
    0 讨论(0)
提交回复
热议问题