我的代码有问题。它没有按照我想要的方式打印出来。

print("Hello Herp, welcome to Derp v1.0 :)")

inFile = input("Herp, enter symbol table file: ")
symTbl = {}
for line in open(inFile):
    i = line.split()
    symTbl[i[0]] = int(i[1])
print("Derping the symbol table (variable name => integer value)...")
for var1 in symTbl:
    print(var1 + " => " + str(symTbl[var1]))

当我打开文本文件时,它会打印出以下内容:
z => 30
y => 20
x => 10

这是不对的,我希望有这样的输出:
x => 10
y => 20
z => 30

原始文本文件是这样的:
x 10
y 20
z 30

最佳答案

或者,您可以对字典进行排序:

for var1 in sorted(symTbl):
    print(var1 + " => " + str(symTbl[var1]))

10-08 01:52