How to add or increment a dictionary entry?

前端 未结 6 852
时光取名叫无心
时光取名叫无心 2020-12-04 16:19

I\'m currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a

6条回答
  •  时光说笑
    2020-12-04 16:56

    Use a defaultdict:

    from collections import defaultdict
    
    foo = defaultdict(int)
    foo[bar] += 1
    

    In Python >= 2.7, you also have a separate Counter class for these purposes. For Python 2.5 and 2.6, you can use its backported version.

提交回复
热议问题