12

I want to add to a value in a dictionary storing counters:

d[key] += 1

but sometimes the key will not exist yet. Checking to see if the key exists seems too ugly. Is there a nice and pythonic one liner for this - add if the key exists, or create the value 1 if the key is not in the dict.keys ?

thanks

2

4 Answers 4

19

you can use

d={}
key='sundar'

d[key]=d.get(key,0)+1
print d
#output {'sundar': 1}
d[key]=d.get(key,0)+1
print d
#output {'sundar': 2}
2
  • 4
    @WeaselFox In fact I like it, I wish it would be mandatory to add a comment to each down vote. Jul 17, 2014 at 11:09
  • @WeaselFox who know there should be restriction if they downvoted they need to comment then only it became valid downvote:( Jul 17, 2014 at 11:09
10

You can use collections.Counter - this guarantees that all values are 1 or more, supports various ways of initialisation, and supports certain other useful abilities that a dict/defaultdict don't:

from collections import Counter

values = ['a', 'b', 'a', 'c']

# Take an iterable and automatically produce key/value count
counts = Counter(values)
# Counter({'a': 2, 'c': 1, 'b': 1})
print counts['a'] # 2
print counts['d'] # 0
# Note that `counts` doesn't have `0` as an entry value like a `defaultdict` would
# a `dict` would cause a `KeyError` exception
# Counter({'a': 2, 'c': 1, 'b': 1})

# Manually update if finer control is required
counts = Counter()
for value in values:
    counts.update(value) # or use counts[value] += 1
# Counter({'a': 2, 'c': 1, 'b': 1})
4
  • but later stage he got new element into the list so again has to follow one of the answer below right? Jul 17, 2014 at 11:13
  • This is probably the best answer. Thanks.
    – WeaselFox
    Jul 17, 2014 at 11:15
  • @sundar you'd just .update the original counts as shown in the second example... Jul 17, 2014 at 11:22
  • That second example solves all issues. What a wonderful little add-on this is.
    – blissweb
    May 16, 2020 at 23:04
7
>>> import collections
>>> d = collections.defaultdict(int)
>>> key = 'foo'
>>> d[key] += 1
>>> d
defaultdict(<type 'int'>, {'foo': 1})
>>> d[key]
1
>>> d[key] += 1
>>> d[key]
2
2
  • nice. I knew there had to be a nicer way.
    – WeaselFox
    Jul 17, 2014 at 11:02
  • 4
    @WeaselFox just be careful to perform an operation... defaultdict triggers the __default__ behaviour on a __getitem__, so if you just did foo[key] where it didn't exist, you'll get an entry of key: 0 in your counter Jul 17, 2014 at 11:07
3

collections.Counter is the best for the specific use case you gave, but for a more general solution that doesn't require importing anything, use dict.setdefault():

d[key] = d.setdefault(key, 0) + 1
1
  • 1
    Note to viewers: with this syntax, the second argument of setdefault should not be the default value, but the default value minus 1. That is because the +1 at the end will always add 1 to it. Aug 22, 2021 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.