0

我有两个字典:

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

将不胜感激。谢谢!

4

1 回答 1

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())
于 2013-04-12T21:57:27.303 回答