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.
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
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