我試着總結兩本詞典這樣的:類型錯誤:不支持的操作數類型(S)爲+: 'dict_items' 和 'dict_items'
my_new_dict = dict(my_existing_dict.items() + my_new_dict.items())
但收到錯誤
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
我做什麼錯誤?
我試着總結兩本詞典這樣的:類型錯誤:不支持的操作數類型(S)爲+: 'dict_items' 和 'dict_items'
my_new_dict = dict(my_existing_dict.items() + my_new_dict.items())
但收到錯誤
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
我做什麼錯誤?
在python3,dict.items()
返回與這顯然不能被添加dict_items
類型的對象。 (在Python 2中,它返回了list
,可以添加它)。
的另一種方式增加對字典的這對py2k和py3k工作:
d = dict1.copy()
d.update(dict2)
當然,還有你想在關鍵的碰撞的情況下發生的事情有些含糊不清。例如如果兩個字典都有key1
,其key1
應該保留在輸出中?或者你應該使用它們的兩個值的組合?在後一種情況下,你可能會想從collections
模塊的東西(無論是defaultdict
或Counter
)
謝謝,它的作品!我討厭2.7> 3.2遷移... – JohnDow
@ VladislavIl'ushin:你真的**應該閱讀文檔。 – SilentGhost
@mgilson:我認爲3+中的'dict.items()'等同於2.6中的'dict.iteritems()',也就是說它是一個迭代器。 –
第一個問題是這是模棱兩可的 - 詞典不能有重複的鍵,所以你不清楚你的意思,如果兩者都包含相同的鍵,會發生什麼?
但是,這裏的主要問題是dictionary views are set-like,所以他們沒有添加實現。
你可能想要的是union:d1.items() | d2.items()
,它會給你一套(key, value)
的元組。如果您將其傳遞給dict()
並且有重複項,則最後一個值將是使用的值。
因此,簡而言之:
dict(d1.items() | d2.items())
當我嘗試這個時,我得到:'TypeError:unhashable type:'dict'' –
lifesaver!好戲,我的朋友! –
旁註:如果你想遍歷兩個字典,你知道他們有獨特的鍵(或者它並不重要,如果你處理相同的密鑰兩次),考慮使用itertools.chain(dict_a,dict_b) – Moberg