Python dictionary increment

后端 未结 6 633
小蘑菇
小蘑菇 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:37

    Any one of .get or .setdefault can be used:

    .get() give default value passed in the function if there is no valid key

    my_dict[key] = my_dict.get(key, 0) + num
    

    .setdefault () create a key with default value passed

    my_dict[key] = my_dict.setdefault(key, 0) + num
    
    0 讨论(0)
  • 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(<function <lambda> at 0x7ff2fe7d37d0>, {12: 3})
    
    0 讨论(0)
  • 2020-12-08 19:46

    What you want is called a defaultdict

    See http://docs.python.org/library/collections.html#collections.defaultdict

    0 讨论(0)
  • 2020-12-08 19:48

    transform:

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

    into the following using setdefault:

    my_dict[key] = my_dict.setdefault(key, 0) + num
    
    0 讨论(0)
  • 2020-12-08 19:50

    There is also a little bit different setdefault way:

    my_dict.setdefault(key, 0)
    my_dict[key] += num
    

    Which may have some advantages if combined with other logic.

    0 讨论(0)
  • 2020-12-08 19:58

    An alternative is:

    my_dict[key] = my_dict.get(key, 0) + num
    
    0 讨论(0)
提交回复
热议问题