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

maven fortify plugin : Unable to load build session with ID XXXXX .. See log file for more details -

c# - Primavera WebServices does not return any data -

android - Display emoji panel with genymotion - keyboard/touch input? -