Use truth-value testing directly with if not my_dict: (or if my_dict: to check if non-empty), which is the idiomatic PEP 8 standard in Python and runs in $O(1)$ constant time by inspecting the dictionary’s internal item count without creating temporary keys, views, or intermediate objects.
Basic Example
config = {}
users = {"alice": 1, "bob": 2}
# 1. Recommended (PEP 8 idiomatic truthiness check — O(1) time):
if not config:
print("Config dictionary is empty")
# Output: Config dictionary is empty
if users:
print(f"Loaded {len(users)} users")
# Output: Loaded 2 users
# 2. When the variable might be `None` OR a dictionary (e.g., optional function argument):
def process_headers(headers: dict[str, str] | None = None) -> None:
if not headers: # Safely catches BOTH None and {}
print("No headers provided")
return
print("Header count:", len(headers))
Key Details & Edge Cases
- Why
if not d:is faster and cleaner thanif len(d) == 0:orif d == {}::- Under the hood, Python’s
bool(d)callsdict.__bool__, which simply checksd->ma_used != 0directly in C without invoking the globallen()builtin or allocating an empty{}dictionary literal to compare against (d == {}).
- Under the hood, Python’s
- Distinguishing an empty dict
{}fromNone(orFalse/0):if not d:evaluates toTruefor any falsy value ({},None,[],"",0,False).- When a function accepts
dict | Noneand you need different behavior forNone(“not passed”) versus{}(“explicitly passed empty dict”), testNoneexplicitly first:if data is None: print("Parameter omitted") elif not data: print("Explicitly passed an empty dict {}")
- Checking if a dictionary contains only
Noneor empty values (not structurally empty):{"a": None, "b": ""}has length2, soif not d:evaluates toFalse. If you want to treat a dictionary whose values are allNone/falsy as empty, checkif not any(d.values()):(orif all(v is None for v in d.values()):).
- Works identically across all Python mapping types (
defaultdict,Counter,OrderedDict,MappingProxyType):- Because
collections.abc.Mappingdefines__bool__via__len__() != 0,if not d:works uniformly acrossdict,collections.defaultdict,collections.Counter,collections.OrderedDict, and read-onlytypes.MappingProxyType.
- Because
- Never write
if len(d.keys()) == 0:orif list(d) == []::- Converting
dto alistcopies all keys in $O(n)$ time and memory just to check whether the dictionary has zero entries.
- Converting
Comparison of Dictionary Emptiness Checks in Python
| Idiom | Time Complexity | Distinguishes {} from None? |
PEP 8 Idiomatic? | Best Used When |
|---|---|---|---|---|
if not d: (Recommended) |
$O(1)$ | No (both {} and None are falsy) |
Yes (official PEP 8 standard) | Standard emptiness checks when d is known to be a dict or when None and {} share the same fallback path. |
if d is not None and not d: |
$O(1)$ | Yes | Yes | Functions accepting dict | None where None (“unset”) and {} (“empty”) require separate handling. |
if len(d) == 0: |
$O(1)$ | Yes (len(None) raises TypeError) |
Acceptable, less concise | Codebases emphasizing explicit length checks or guarding against silent acceptance of None. |
if d == {}: |
$O(1)$ | Yes (None == {} is False) |
Discouraged by PEP 8 | Almost never—allocates an empty dict literal and performs a full equality check unnecessarily. |
You must log in or register to comment.
