繁体   English   中英

向列表理解中创建的每个字典添加条目

[英]Adding an entry to each dictionary created in a 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,我想一行完成。 我可以吗?

问题在于:

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

dict.update()方法返回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 ]  

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM