2015-02-24 34 views
1

我使用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 ] 

当然我可以用一个循环列表解析后追加额外的入口 - 但这是蟒蛇,我想这样做的一条线。我可以吗?

+0

你得到了什么确切的错误? – Nilesh 2015-02-24 06:08:41

+0

不要使用列表作为变量名称。 – 2015-02-24 06:08:54

+0

@drew而不是发布代码,你能提供一个例子吗? – 2015-02-24 06:15:40

回答

1

的问题:

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

在于.update()方法的dict返回None因为它是一个mutilator。试想一下:

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 ] 

它从旧的值的连接创建一个新的字典。