How to add or increment a dictionary entry?

前端 未结 6 854
时光取名叫无心
时光取名叫无心 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:51

    The dict's get() method takes an optional second parameter that can be used to provide a default value if the requested key is not found:

    foo[bar] = foo.get(bar, 0) + 1
    

提交回复
热议问题