python - 创建具有默认值的字典列表

标签 python python-2.7

我有一组字符串,例如:

('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/

相关文章:

python - 在 python 中使用正则表达式解析 IP

python - 查找(并记录)numpy 数组切片的最大值

javascript - Django 渲染一个 "in exception"的页面而不是一个可以帮助调试的页面

python - 排序和唯一与集合

python - 使用 Python 和 Flask 流式传输数据引发 RuntimeError : working outside of request context

python - 使用正确的编码检索电子邮件内容

python - 用 Python 编码的图像锐化算法

Python — 检查字符串是否包含西里尔字符

python - 如何有条件地连接

python - 如何在python中的字符串中的双引号内显示​​单引号