Python dictionary increment

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

    What you want is called a defaultdict

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

提交回复
热议问题