我有两本词典:
sampleOne= {'a':4, 'b':7, 'c':3, 'd':5}
sampleTwo= {'a':6, 'b':3, 'c':7, 'd':2}
我尝试过使用:
for key,value in sampleOne:
print(key,value)
for key,value in samepleTwo:
print(key,value)
但是这种方法不起作用,我希望结果看起来像这样:
a 4 6
b 7 3
c 3 7
d 5 2
然而我看起来像这样:
a 4
b 7
c 3
d 5
a 6
b 3
c 7
d 2
非常感谢帮助。谢谢!
答案 0 :(得分:3)
>>> sampleOne= {'a':4, 'b':7, 'c':3, 'd':5}
>>> sampleTwo= {'a':6, 'b':3, 'c':7, 'd':2}
>>> for k in sampleOne.viewkeys() | sampleTwo.viewkeys(): # On Py 3 use .keys() instead
print k, sampleOne.get(k, 0), sampleTwo.get(k, 0)
a 4 6
c 3 7
b 7 3
d 5 2
如果您需要这些字母,请更改此行:
for k in sampleOne.viewkeys() | sampleTwo.viewkeys()
到
for k in sorted(sampleOne.viewkeys() | sampleTwo.viewkeys())