Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest equality of two nested dictionaries

Which assert statement should I use, if I want to compare 2 dicts that have a list of values inside them.

For example, if these dicts are like this:

{'other_parts': ['director', 'head', 'chief', 'leader', 'administrator'], 'headword': 'manager', 'language': 'en'}

{'other_parts': ['director', 'chief', 'head', 'leader', 'administrator'], 'headword': 'manager', 'language': 'en'}

I want comparison of these two dicts to pass, because I don't care about order in nested list. Comparison with assertDictEqual fails, because nested lists of other_parts are not in the same order, I presume.

like image 646
primoz Avatar asked Nov 01 '25 04:11

primoz


1 Answers

If you don't care about order, you'll have to sort the lists or use a set (only if you're sure the lists won't contain duplicates!)

dict1['other_parts'] = sorted(dict1['other_parts'])
dict2['other_parts'] = sorted(dict2['other_parts'])
assertDictEqual(dict1, dict2)

which can also be used as

from unittest import TestCase
TestCase().assertEqual(dict1, dict2)

See docs : https://docs.python.org/3/library/unittest.html#unittest.TestCase.addTypeEqualityFunc

like image 60
Nee Avatar answered Nov 03 '25 18:11

Nee