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'] = 1
  • get has been my favorite
    • mainly because of its syntax
    • but i haven’t really thought about this question
  • performance wise, get is 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 just want to set a default value, get makes the most sense
    • if allows us to do something that get doesn’t:
if 'x' in d:
	d['x'] += 1
else:
	call_a_function()

up

down

reference