Reputation: 2990
I am looking for a "update and insert" operation for dict, there is a common job: for given keys in a list, for each key update the value in dict. but if the key don't exist in dict, insert a default value into the dict then update like:
for k in list:
dict[k] += 2
If k is not in dict's keys, do dict[k] = 0
and dict[k] += 2
like c++'s std::map
Is there a simple way? I don't want write a if-else
Upvotes: 0
Views: 250
Reputation: 25954
A few ways:
dict.get
for k in li:
d[k] = d.get(k,0) + 2
setdefault
for k in li:
d[k] = d.setdefault(k,0) + 2
You'll notice that this is basically equivalent to the get
syntax. The difference between the two is that the call to setdefault
actually creates the default value if it doesn't yet exist, so you could alternatively write:
for k in li:
d.setdefault(k,0)
d[k] += 2
use a defaultdict
from collections import defaultdict
d = defaultdict(int)
for k in list:
d[k] += 2
(don't name your lists list
, don't name your dicts dict
; those names shadow the built-in types)
Upvotes: 2
Reputation: 3307
from collections import defaultdict
d = defaultdict(int)
d['whatever'] += 2
Upvotes: 1
Reputation: 239473
When you do
dict[k] += 2
It means that
dict[k] = dict[k] + 2
So, Python tries to get the value for the key k
and it doesn't find one. So, it fails. But we can use dict.get
which will return a default value when a key is not found. It can be used like this
for k in my_list:
d[k] = d.get(k, 0) + 2
Here, we ask the dictionary object to return 0 if the key is not found. And then we assign the value of the right hand expression to d[k]
, which will either update/create a new key.
Upvotes: 1