Trying to assert that two dictionaries that have nested contents are equal to each other (order doesn't matter) with pytest. What's the pythonic way to do this?
Use == operator to check if the dictionaries are equal You can create the dictionaries with any of the methods defined in Python and then compare them using the == operator. It will return True the dictionaries are equals and False if not.
You can use the == operator, and it will work. However, when you have specific needs, things become harder. The reason is, Python has no built-in feature allowing us to: compare two dictionaries and check how many pairs are equal.
Check if two nested dictionaries are equal in Python To do this task, we are going to use the == operator and this method will help the user to check whether the two given dictionaries are equal or not.
You can use set intersection on the dictionaries keys() . Then loop over those and check if the values corresponding to those keys are identical.
Don't spend your time writing this logic yourself. Just use the functions provided by the default testing library unittest
from unittest import TestCase TestCase().assertDictEqual(expected_dict, actual_dict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With