Check if a Dictionary is Empty
Quick Overview
An empty dict is falsy, so `if not d:` is the idiomatic check. `d == {}` is true for it as well, but cannot tell an empty dict from `None`: only `is None` does that.
Deep Dive
1. The Challenge: Dictionary Validation
Create a function is_empty(dictionary) that returns True if a dictionary is empty, and False otherwise.
2. Why It Matters
Dictionaries are Python's key-value lookup data structure. Checking if a dictionary contains data before reading keys prevents runtime errors.
3. The Python Solution
An empty dictionary {} is falsy in Python. You can check not dictionary or len(dictionary) == 0:
def is_empty(dictionary):
return len(dictionary) == 0
# Pythonic Truthiness Alternative
def is_empty_pythonic(dictionary):
return not dictionary
# Testing our function
print(is_empty({})) # Output: True
print(is_empty({"a": 1})) # Output: False
print(is_empty_pythonic({})) # Output: True
4. Dictionary Truthiness Model
{}(Length 0) evaluates toFalsein boolean context.- Any dictionary containing 1+ keys evaluates to
True.
5. Common Mistakes
- KeyError on Missing Keys: Attempting to read a missing key
dict["key"]from an unverified dictionary raises aKeyError. Usedict.get("key", fallback)for safe property access!
6. Next Steps
Use dict.get() for safe property reads. Next, let's repeat list items N times!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.