我在一个名为
my_text.txt
:
David: 2
Barbara: 97.2
David: negative
William:
Lynn: 725
Nancy : 87
David: 54
Lewis: 18.30
Sue: 3193.74
James: 41.73
David: 974.1
import collections
def make_dictionary(file_name):
d = collections.defaultdict(float)
with open(file_name, 'r') as file:
for line in file:
line = line.strip()
# skip blank lines
if line == '':
continue
# split on the colons
elif ':' in line:
key, val = line.split(':')
d[key.strip()] += val.strip()
return d
make_dictionary('my_text.txt')
我希望能够增加字典中的值。例如,David的密钥/值对是:
David : 1030.1
(文件中3个值的总和)
TypeError: unsupported operand type(s) for +=: 'float' and 'str'
你知道怎么解决这个问题吗?
谢谢!