我有一组字符串,例如:
('abc', 'def', 'xyz')
我想将这些字符串用作键“类型”的值,并为每个字符串关联 2 个额外的键值对,为每个额外的键提供默认值,如下所示:
resulting_list_of_dicts = [{'type' : 'abc' ,'extra_key1' : 0, 'extra_key2' : 'no'},
{'type' : 'def' ,'extra_key1' : 0, 'extra_key2' : 'no'},
{'type' : 'xyz' ,'extra_key1' : 0, 'extra_key2' : 'no'}]
如何在 Python 2.7 中(巧妙地)做到这一点?
最佳答案
您可以只使用列表理解。我假设这会返回您想要的内容
strings = [ 'abc', 'def', 'xyz' ]
result = [ { 'type': type, 'extra_key1':0, 'extra_key2':'no' } for type in strings ]
或
strings = [ 'abc', 'def', 'xyz' ]
defaults = { 'extra_key1':0, 'extra_key2':'no' }
result = [ { 'type': type }.update( defaults ) for type in strings ]
关于python - 创建具有默认值的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18668055/