python dict, if, get, and try-except
tags: learning programming
content
To fetch a value from dictionary, when do we use if, or get, or try-except
d = {'a': 1}
if 'a' in d:
d['a'] += 1
else:
d['a'] = 1
d['a'] = d.get('a', 0) + 1
try:
d['a'] += 1
except KeyError:
d['a'] = 1gethas been my favorite- mainly because of its syntax
- but i haven’t really thought about this question
- performance wise,
getis actual slow - when we write code, performance is usually not our top priority
- it’s more about readability and the 语义 (underlying meaning) of these different methods
- the most obvious is
try-except- when we use
try-except, we are implicitly implying that this is an error (Exception)
- when we use
- when we just want to set a default value,
getmakes the most sense ifallows us to do something thatgetdoesn’t:
- the most obvious is
if 'x' in d:
d['x'] += 1
else:
call_a_function()