2015-02-24 43 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 ] 

它從舊的值的連接創建一個新的字典。