简体   繁体   中英

python dict add and modify operation

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

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)

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.

from collections import defaultdict
d = defaultdict(int)
d['whatever'] += 2
dict[k]=dict.get(k,0)+=2

是你会怎么做的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM