Python dictionary increment

后端 未结 6 632
小蘑菇
小蘑菇 2020-12-08 19:03

In Python it\'s annoying to have to check whether a key is in the dictionary first before incrementing it:

if key in my_dict:
  my_dict[key] += num
else:
  m         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 19:42

    You have quite a few options. I like using Counter:

    >>> from collections import Counter
    >>> d = Counter()
    >>> d[12] += 3
    >>> d
    Counter({12: 3})
    

    Or defaultdict:

    >>> from collections import defaultdict
    >>> d = defaultdict(int)  # int() == 0, so the default value for each key is 0
    >>> d[12] += 3
    >>> d
    defaultdict( at 0x7ff2fe7d37d0>, {12: 3})
    

提交回复
热议问题