dictionary - Handle missing keys with numeric types in Python -
for mutable types, such list, instead of using if else, can deal missing key issues this:
dic = {'key1':[1, 2], 'key2':[1]} dic.setdefault('key3', []).append(1)   which checks 'key3' in dic once.
but immutable types, such integer, cannot use setdefault() this:
dic = {'key1':3, 'key2':5} dic.setdefault('key3', 0) += 1   since setdefault() return integer 0 instead of variable dic['key3']
i'm not sure how deal elegantly, example best can this:
dic = {'key1':3, 'key2':5} dic['key3'] = 1 if 'key3' not in dic else dic['key3'] + 1   but code checks 'key3' in dic twice , use memory dic['key3'] + 1 if 'key3' exists.
any suggestions?
you can use .get(..) specify default value, like:
dic['key3'] = dic.get('key3',0) + 1  .get(key,default=none) performs lookup on dictionary. in case fails find key, return default.
but think in case, better use counter:
from collections import counter  counter = counter({'key1':3, 'key2':5}) counter['key3'] += 1  a counter assumes if key not present in database, value zero.
Comments
Post a Comment