Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you test that two dictionaries are equal with pytest in python

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?

like image 989
John Mike Avatar asked Nov 09 '17 12:11

John Mike


People also ask

How do I check if two dictionaries are equal in Python?

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.

Can we compare 2 dictionaries in Python?

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.

How do you check if two dictionaries have the same keys and values?

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.

How do you compare two dictionaries with the same key in Python?

You can use set intersection on the dictionaries keys() . Then loop over those and check if the values corresponding to those keys are identical.


1 Answers

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) 
like image 141
Vincent Claes Avatar answered Sep 22 '22 04:09

Vincent Claes