简体   繁体   中英

Bast way to update a value in a dict

I have a dict that contains parameters. I want to consider that any unspecified parameter should be read as a zero. I see several ways of doing it and wonder which one is recommended:

parameters = {
    "apples": 2
}

def gain_fruits0 (quantity, fruit):
    if not fruit in parameters :
        parameters[fruit] = 0
    parameters[fruit] += quantity

def gain_fruits1 (quantity, fruits):
    parameters[fruit] = quantity + parameters.get(fruit,0)

parameters is actually way bigger than that, if that is important to know for optimization purposes.

So, what would be the best way? gain_fruits0, gain_fruits1, or something else?

This is a typical use of defaultdict , which works exactly like a regular dictionary except that it has the functionality you're after built in:

>>> from collections import defaultdict
>>> d = defaultdict(int)  # specify default value `int()`, which is 0
>>> d['apples'] += 1
>>> d
defaultdict(int, {'apples': 1})
>>> d['apples']  # can index normally
1
>>> d['oranges']  # missing keys map to the default value
0
>>> dict(d)  # can also cast to regular dict
{'apples': 1, 'oranges': 0}

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