jsj
jsj

Reputation: 9421

Incrementing values of potentially empty keys of a python dictionary

Is there a more correct way to do the following:

if a in dic.keys():
    dic[a] += 1
else:
    dic[a] = 1

I.e. to increment values corresponding to keys in a dictionary, when those keys may not be present.

Upvotes: 1

Views: 1614

Answers (4)

user647772
user647772

Reputation:

Use dict.get:

dic[a] = dic.get(a, 0) + 1

Upvotes: 9

Tim
Tim

Reputation: 12174

You can use a defaultdict to provide a default value for keys not present in the dictionary.

>>> d = defaultdict(int)
>>> d[1] += 1
>>> d[1]
    1
>>> d[5]
    0

Upvotes: 7

Hans Then
Hans Then

Reputation: 11322

You could use collections.Counter()

dic = collections.Counter()
dic['a'] += 1
dic['b'] # will be zero

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

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

you can use dict.setdefault():

In [12]: dic=dict(zip(('a','b'),[0]*2))

In [13]: dic
Out[13]: {'a': 0, 'b': 0}

In [14]: dic['c']=dic.setdefault('c',0)+1

In [15]: dic
Out[15]: {'a': 0, 'b': 0, 'c': 1}

In [16]: dic['a']=dic.setdefault('a',0)+1

In [17]: dic
Out[17]: {'a': 1, 'b': 0, 'c': 1}

using a loop:

In [18]: dic=dict(zip(('a','b'),[0]*2))

In [19]: for x in ('a','b','c','a'):
   ....:     dic[x]=dic.setdefault(x,0)+1
   ....:     

In [20]: dic
Out[20]: {'a': 2, 'b': 1, 'c': 1}

Upvotes: 1

Related Questions