How to Assert Dictionary Equality in pytest: Simple Guide
In pytest, you can assert that two dictionaries are equal using the simple
assert dict1 == dict2 statement. Pytest will automatically compare keys and values and show differences if the assertion fails.Syntax
Use the assert keyword followed by the equality check between two dictionaries. Pytest handles the comparison and reports detailed differences if they are not equal.
dict1: The first dictionary to compare.dict2: The second dictionary to compare.==: Checks if both dictionaries have the same keys and corresponding values.
python
assert dict1 == dict2Example
This example shows how to write a pytest test function that asserts two dictionaries are equal. If they differ, pytest will show which keys or values do not match.
python
def test_dict_equality(): expected = {"name": "Alice", "age": 30, "city": "Paris"} actual = {"name": "Alice", "age": 30, "city": "Paris"} assert actual == expected
Output
============================= test session starts ==============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ===============================
Common Pitfalls
Common mistakes include:
- Using
assert dict1 is dict2which checks identity, not equality. - Comparing dictionaries with different key types or missing keys.
- Ignoring nested dictionaries where deep equality is needed.
Always use == for value equality, not is.
python
def test_wrong_assert(): dict1 = {"a": 1} dict2 = {"a": 1} # Wrong: checks if both are the same object (will fail) # assert dict1 is dict2 # Right: checks if contents are equal assert dict1 == dict2
Quick Reference
| Action | Code Example | Description |
|---|---|---|
| Check dict equality | assert dict1 == dict2 | Passes if both dicts have same keys and values |
| Check dict identity (not recommended) | assert dict1 is dict2 | Checks if both variables point to same object |
| Compare nested dicts | assert dict1 == dict2 | Works if nested dicts have same structure and values |
Key Takeaways
Use assert dict1 == dict2 to check dictionary equality in pytest.
Avoid using 'is' for dictionary comparison as it checks object identity, not content.
Pytest shows detailed differences when dictionary assertions fail.
Ensure nested dictionaries are structured the same for equality to pass.
Simple assert statements are enough; no extra pytest functions needed.