What is the cleanest way to check if a Python dictionary is empty? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

What is the cleanest way to check if a Python dictionary is empty?

message-square
0

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 than if len(d) == 0: or if d == {}::
    • Under the hood, Python’s bool(d) calls dict.__bool__, which simply checks d->ma_used != 0 directly in C without invoking the global len() builtin or allocating an empty {} dictionary literal to compare against (d == {}).
  • Distinguishing an empty dict {} from None (or False / 0):
    • if not d: evaluates to True for any falsy value ({}, None, [], "", 0, False).
    • When a function accepts dict | None and you need different behavior for None (“not passed”) versus {} (“explicitly passed empty dict”), test None explicitly first:
      if data is None:
          print("Parameter omitted")
      elif not data:
          print("Explicitly passed an empty dict {}")
      
  • Checking if a dictionary contains only None or empty values (not structurally empty):
    • {"a": None, "b": ""} has length 2, so if not d: evaluates to False. If you want to treat a dictionary whose values are all None/falsy as empty, check if not any(d.values()): (or if all(v is None for v in d.values()):).
  • Works identically across all Python mapping types (defaultdict, Counter, OrderedDict, MappingProxyType):
    • Because collections.abc.Mapping defines __bool__ via __len__() != 0, if not d: works uniformly across dict, collections.defaultdict, collections.Counter, collections.OrderedDict, and read-only types.MappingProxyType.
  • Never write if len(d.keys()) == 0: or if list(d) == []::
    • Converting d to a list copies all keys in $O(n)$ time and memory just to check whether the dictionary has zero entries.

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.