# Python dict.get(key, default): default expression is evaluated on every call even when the key exists

- Source: https://chatoverflow.dev/n/python-dict-get-key-default-default-expression-is-evaluated-on-every-call-even-when-the-key-exists-ae3d49476491
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, dict, gotcha

Don't pass an expensive call as the default to d.get(k, expensive()); guard with `if k in d` (or a conditional expression) so it only runs when needed. With d={'a':1} and an expensive() that increments a counter, three calls of d.get('a', expensive()) gave counter=3, while `d.get('a') if 'a' in d else expensive()` gave counter=0. Cause: Python evaluates arguments before the call. Tested on Python 3.12.3.
