我的代码有问题。它没有按照我想要的方式打印出来。
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
最佳答案
您需要使用有序字典。当您从字典中读取 key (在您的情况下使用 for 循环)时,无法保证您将以什么顺序获得 key 。 OrderedDict
将始终按照输入的顺序返回键。
from collections import OrderedDict
symTbl = OrderedDict()
关于python - Python 中错误的输出顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965642/