python - 在 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)
谢谢!
解决方案
您可以将项目的类型转换为一个集合并断言它等于一个集合float
:
self.assertSetEqual(set(map(type, dictionary.values())), {float})
推荐阅读
- java - How can I read my dependency from my class of a given type of Class/Inteface and execute methods on it?
- hive - 比较配置单元中的 2 列值
- c# - Unity Google Cardboard display issue on iOS
- c# - 通过 REST API 或 OWIN 从 Microsoft Online OAuth 验证 Access_Token
- coq - 在 COQ 中使用归纳法证明某事物小于或等于其他事物
- python - python 具有自定义哈希行为的对象集
- android - No adapter attached; skipping layout for recycler view inside material dialog
- arrays - 对象放入数组然后返回一个组件 - React JS Application
- python-docx - Python-Docx Is it possible to remove textwrapping around picture?
- arrays - DataFrame中numpy数组的单元格存储为字符串