如何在Python的OrderedDict列表中针对重复name值抛出AssertionError
Check for Duplicate "name" Values in OrderedDict List
Your original code was checking for duplicate keys across all dictionaries, which isn’t what you need. To specifically detect duplicate values for the "name" key and throw an AssertionError, here’s how to adjust your code:
Modified Code
import unittest from collections import OrderedDict # Your existing dict_lists definition dict_lists = [[ OrderedDict([('name', 'Good check'), ('url', 'https://www.facebook.com/'), ('lag', 10), ('tags', ['team:team 4', 'section 1', 'section 2']), ('headers', OrderedDict([('Location', 'http://facebook.com/')]))]), OrderedDict([('name', 'Bad check'), ('url', 'https://www.google.com/'), ('lag', 5), ('tags', ['team:team 1'])]), OrderedDict([('name', 'Bad check'), ('url', 'https://www.microsoft.com/'), ('lag', 5), ('tags' , ['team:team 5'])]) ]] class TestUniqueNames(unittest.TestCase): def test_unique_names(self): seen_names = [] for dict_list in dict_lists: for dictionary in dict_list: current_name = dictionary['name'] # Check if the name has already been seen self.assertNotIn( current_name, seen_names, f"Duplicate name detected: '{current_name}'" ) seen_names.append(current_name) if __name__ == '__main__': unittest.main()
Key Changes Explained:
- Track Seen Names: We maintain a list
seen_namesto keep track of all "name" values we’ve encountered so far. - Focus on "name" Value: Instead of iterating over all keys in the dictionary, we directly extract the value of the "name" key from each OrderedDict.
- Clear Assertion: Using
self.assertNotIn, we check if the current name is already inseen_names. If it is, the test fails with a descriptive error message pointing out the duplicate.
What Happens with Your Example?
When you run this test, it will immediately throw an AssertionError because "Bad check" appears twice. The error message will look like this:
AssertionError: 'Bad check' unexpectedly found in ['Good check', 'Bad check'] : Duplicate name detected: 'Bad check'
This exactly meets your requirement of detecting duplicate "name" values and failing the test when they occur.
内容的提问来源于stack exchange,提问作者nara_l
相关产品推荐
相关产品推荐

