使用默认值创建字典列表

时间:2013-09-06 23:30:54

标签: python python-2.7

我有一组字符串,如:

('abc', 'def', 'xyz')

我希望将这些字符串用作键'type'的值,并将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中巧妙地做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以使用列表理解。我假设这会返回你想要的东西

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 ]