Reputation: 9421
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
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
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
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