字典应该有“N' N'关键之前' D'但是当它贯穿“D'键是第一个,为什么追加函数将D添加到前面而不是字典的结尾?
Binary.txt是:
N = N D
N = D
D = 0
D = 1
python文件是
import sys
import string
from collections import defaultdict
#default length of 3
stringLength = 3
#get last argument of command line(file)
if len(sys.argv) == 1:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
elif len(sys.argv) == 2:
#get a length from user
try:
stringLength = int(input('Length? '))
filename = sys.argv[1]
except ValueError:
print("Not a number")
elif len(sys.argv) == 3:
filename = sys.argv[2]
stringLength = sys.argv[1].split('l')[1]
else:
print("Invalid input!")
#checks
print(stringLength)
print(filename)
def str2dict(filename):
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
line = line.rstrip('\n')
result[line[0]].append(line.split('=')[1])
print(result)
return result
答案 0 :(得分:1)
标准dict
是无序的。您应该使用collections.OrderedDict
代替。
OrderedDict是一个记住首次插入密钥的顺序的字典。如果新条目覆盖现有条目,则原始插入位置保持不变。删除一个条目并重新插入它将把它移到最后。
答案 1 :(得分:0)