Python dictionary increment
Asked Answered
A

7

48

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:
  my_dict[key] = num

Is there a shorter substitute for the four lines above?

Actaeon answered 20/10, 2012 at 20:0 Comment(1)
can you do this same thing for two values?Excide
T
90

An alternative is:

my_dict[key] = my_dict.get(key, 0) + num
Thundershower answered 20/10, 2012 at 20:6 Comment(4)
can you do it for multiple values? i mean increment more than one valueExcide
Without a loop? As dict doesn't provide a way to access multiple elements in a single expression I don't see how.Thundershower
With a loop just like the OP writes in his question, but incrementing two values per key not oneExcide
I think you should ask a new question for that.Thundershower
C
33

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})
Coussoule answered 20/10, 2012 at 20:1 Comment(4)
For lambda: 0, you can just say, int.Meingoldas
@hughdbrown: Thanks, I never knew that.Coussoule
@Meingoldas without your comment I would never have understood what a defaultdict was doing. Thank you.Conveyance
It's a pity that the docs don't mention that Counter also supports the default 0 functionality. I have been using Nicola's solution until now, but it's much nicer without it.Inessential
L
9

What you want is called a defaultdict

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

Lisettelisha answered 20/10, 2012 at 20:1 Comment(0)
P
8

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
Paderewski answered 20/10, 2012 at 20:5 Comment(0)
E
4

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.

Eula answered 14/7, 2018 at 18:38 Comment(0)
L
1

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
Lade answered 17/4, 2020 at 22:43 Comment(0)
U
1

A solution to shorten the condition can be the following sample:

dict = {}
dict['1'] = 10
dict['1'] = dict.get('1', 0) + 1 if '1' in dict else 1
print(dict)
Unemployment answered 3/7, 2022 at 13:13 Comment(1)
dict is the build-in name of dictionaries. The answer is functunally equivalent to the already accepted one with an unneccessary inline if function.Cotterell

© 2022 - 2024 — McMap. All rights reserved.