首页 > 解决方案 > 在 Python 字典中断言所有值的数据类型的更好方法

问题描述

我正在构建一个单元测试,它断言/检查字典中的所有值是否具有相同的数据类型:float.

Python 版本 3.7.4

假设我有四个不同的字典:

dictionary1: dict = {
    "key 1": 1.0,
}

dictionary2: dict = {
    "key 1": "1.0",
}

dictionary3: dict = {
    "key 1": 1.0,
    "key 2": 2.0,
    "key 3": 3.0
}

dictionary4: dict = {
    "key 1": "1",
    "key 2": "2",
    "key 3": 3
}

和这样的单元测试用例:

class AssertTypeUnitTest(unittest.TestCase):

    def test_value_types(self):
        dictionary: dict = dictionary
        self.assertTrue(len(list(map(type, (dictionary[key] for key in dictionary)))) is 1 and
                            list(map(type, (dictionary[key] for key in dictionary)))[0] is float)


if __name__ == "__main__":
    unittest.main()

预期的结果是,AssertionError如果字典中有一个值不是,它会抛出一个float,即它会为dictionary2而不是为dictionary1

现在,虽然测试确实适用于 1 key-value pair ,但在无需添加另一个 for 循环的情况下dictionary3,我将如何为多个 key-value 对执行此操作?dictionary4

IE

for type in list(map(type, (dictionary[key] for key in dictionary))):
    self.assertTrue(type is float)

谢谢!

标签: pythonunit-testingdictionarytypesassertion

解决方案


您可以将项目的类型转换为一个集合并断言它等于一个集合float

self.assertSetEqual(set(map(type, dictionary.values())), {float})

推荐阅读