我有一本字典,我想用它作为模板来生成多个带有更新字典项的字典。此列表应用作 pytest 中单元测试中用于测试目的的数据集。
我在我的代码中使用以下构造(不包括检查):
def _f(template,**kwargs):
result = [template]
for key, value in kwargs.items():
result = [dict(template_item,**dict([(key,v)])) for v in value for template_item in result]
return result
template = {'a': '', 'b': '', 'x': 'asdf'}
r = _f(template, a=[1,2],b=[11,22])
pprint(r)
[{'a': 1, 'b': 11, 'x': 'asdf'},
{'a': 2, 'b': 11, 'x': 'asdf'},
{'a': 1, 'b': 22, 'x': 'asdf'},
{'a': 2, 'b': 22, 'x': 'asdf'}]
我想问一下,该构造是否用于构建足够好 - 可能它可以写得更有效。
这是准备测试数据的正确方法吗?
编辑: 特别是我不确定
[dict(template_item,**dict([(key,v)])) for v in value for template_item in result]
和
dict(template_item,**dict([(key,v)]))
在我考虑 dict.update() 但不适合理解之前,因为它不返回字典。
然后我在考虑简单的语法,比如
d = {'aa': 11, 'bb': 22}
dict(d,x=33,y=44)
{'aa': 11, 'bb': 22, 'x': 33, 'y': 44}
但我无法通过变量传递键值。创建 dict 只是为了解压它对我来说听起来适得其反。
慕斯709654
相关分类