Help in implementation

This is a general doubt:
Say I have dict in python:
dict={1:2,3:1,6:5,9:0}
which is better implementation?

dict={1:2,3:1,6:5,9:0}
x=2
if x in dict:
    dict[x]+=5
else:
    dict[x]=5

or

dict={1:2,3:1,6:5,9:0}
x=2
try:
    dict[x]+=5
except:
    dict[x]=5

if and else statement would be better. try and except generally used to handle error.

2 Likes

look into
from collections import defaultdict
if u access a key that does not exist, it is initialized with some value (if not specified 0)
it is much more powerful than standard dictionary

Some value??
What is the use then?
I want to initialize it to 0, then only it is helpful.