How does collections.defaultdict work?

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

    Without defaultdict, you can probably assign new values to unseen keys but you cannot modify it. For example:

    import collections
    d = collections.defaultdict(int)
    for i in range(10):
      d[i] += i
    print(d)
    # Output: defaultdict(, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9})
    
    import collections
    d = {}
    for i in range(10):
      d[i] += i
    print(d)
    # Output: Traceback (most recent call last): File "python", line 4, in  KeyError: 0
    

提交回复
热议问题