我正在尝试创建一个将值保存到键的字典,如果该键已经存在,则该值将附加到键以生成值列表。我使用python 3所以dict.has_key方法已经弃用了,有人可以指点我正确的方向吗?
Binary.txt:
N = N D
N = D
D = 0
D = 1
import sys
import string
#default length of 3
stringLength = 3
#get last argument of command line(file)
filename1 = sys.argv[-1]
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
#checks
print(stringLength)
print(filename)
def str2dict(filename="Binary.txt"):
result = {}
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
#append info
print(line)
line = line.rstrip('\n')
if line[0] in result:
result[line[0]].append(line.split('=')[1])
else:
result[line[0]] = line.split('=')[1]
print (result)
return result
print (str2dict("Binary.txt"))
答案 0 :(得分:2)
使用defaultdict,如果密钥存在,我们会追加该项目,如果不存在,我们将创建密钥,然后追加该项目:
from collections import defaultdict
d = defaultdict(list)
d[key].append(item)
在您的代码中:
result = defaultdict(list)
然后简单地说:
result[line[0]].append(line.split('=')[1])
无需检查密钥是否存在。