How does collections.defaultdict work?

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

提交回复
热议问题