在列表推导中创建的每个字典中添加一个条目

时间:2015-02-24 06:06:24

标签: python list-comprehension

我正在使用Python 2.6.6,我想这样做:

result = [ otherMethod.getDict(x).update({'foo': x.bar}) for x in someList ]  

即。我有一个返回对象属性字典的方法,我在列表构建中调用它来构建这些字典的列表,我想为每个字典添加一个额外的属性。但是上面的语法给我留下了NoneType的列表,如下所示:

result = [ otherMethod.getDict(x) + {'foo': x.bar} for x in someList ]  

当然我可以在列表理解之后使用一个循环来追加附加条目 - 但这是python,我想在一行中完成。我可以吗?

1 个答案:

答案 0 :(得分:1)

问题:

result = [ otherMethod.getDict(x).update({'foo': x.bar}) for x in list ]  

.update() dict方法返回None,因为它是一个破坏者。考虑一下:

result = [ (d.update({'foo': x.bar}), d)[1] for d, x in ((otherMethod.getDict(x), x) for x in list) ]

如果我们不允许使用像:

这样的本地函数
def update(d, e)
    d.update(e)
    return d

result = [ update(otherMethod.getDict(x), {'foo': x.bar}) for x in list ]

如果您不想让返回的dict变异,请考虑:

result = [ dict(otherMethod.getDict(x).values() + ({'foo': x.bar}).values()) for x in list ]  

从旧的值的串联中创建一个新的dict。