Reputation: 8288
I have a piece of code which is iterating a list and then accumulate the values in a dict based on the keys, the ugly part is that I need to check if the key already exist in the dict, if not then I need to set the value to zero first.
I'm wondering if there's more elegant style to implement this:
for r in records:
if not d.has_key(r[0]):
d[r[0]] = 0
d[r[0]] += r[1]
And further more, if the value is a list, then how to rewrite the following code:
for (key, value) in records:
if not d.has_key(key):
d[key] = []
d[key].append(value)
Upvotes: 1
Views: 121
Reputation: 2428
This is a common pattern when working with dicts in python so there is a defaultdict in the collections module. This lets you specify a default value for keys that are not in the dictionary. e.g:
from collections import defaultdict
d = defaultdict(int)
d[10] += 1
In [19]: dict(d)
Out[19]: {10: 1}
As you see, you don't have to check if the key exists in the dict if you use defaultdict.
d = defaultdict(int)
for r in records:
d[r[0]] += r[1]
Upvotes: 3
Reputation: 239443
You can use the builtin dict.get
method to get the default value, like this
for r in records:
d[r[0]] = d.get(r[0], 0) + r[1]
The second argument to dict.get
is the default value to be returned if the key is not there in the dictionary.
Even better, you can unpack the values, like this
for (key, value) in records:
d[key] = d.get(key, 0) + value
Upvotes: 3