try - except KeyError block in Python -



try - except KeyError block in Python -

x tuple: (x1, x2)

try: clusters[bestmukey].append(x) # statment 1 except keyerror: clusters[bestmukey] = [x] # statement 2

(1) how statement 1 , statement 2 different things?

(2) why separated statements needed?

clusters[bestmukey].append(x) requires clusters[bestmukey] exist , list can appended to. if clusters not have right key, raise keyerror.

clusters[bestmukey] = [x] work (as long clusters dictionary, i'm assuming), , sets value new list 1 element.

the effect of code create list new single value if key not exist, or add together value existing list if exist.

the same effect achieved without try/except using defaultdict. defaultdict wraps logic itself.

python keyerror

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -