How to add or increment a dictionary entry?

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

    For Python >= 2.5 you can do the following:

    foo[bar] = 1 if bar not in foo else foo[bar]+1
    

提交回复
热议问题