2016-01-09 49 views

回答

4

使用itertools.chain

from itertools import chain 

for word, cls in chain(self.spam.items(), self.ham.items()): 
    print(word, cls) 
3

自Python2,dict.items()将产生(key,value)元组列表,您可以连接两个列表,而在Python3,它会返回一个viewing object,因此我们需要将其转换为list,所以下面也做的一种方法:

>>> d1 = {1:'ONE',2:'TWO'} 
>>> d2 = {3:'THREE', 4:'FOUR'} 
>>> dict_chained = d1.items() + d2.items() #Python2 
>>> dict_chained = list(d1.items())+list(d2.items())) #Python3 
>>> for x,y in dict_chained: 
    print x,y 


1 ONE 
2 TWO 
3 THREE 
4 FOUR 
>>> 
+0

注意的是Python 3'dict.items()'返回一个[view object](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects),它不支持连接。 –

+0

@eugeney ..谢谢你的头... ...将更新与更通用的解决方案 –