在python中dict的文本文件?

时间:2016-11-06 23:16:21

标签: python

我有一个文本文件,其中包含:

Alice;Lodging;49.99;10/12/2016
Bob;Dining;8.42;10/13/2016
Charles;Lodging;55.76;10/14/2016
David;Dining;19.95;10/15/2016
Eve;Rental;105.99;10/16/2016
Frank;Rental;raft;10/17/2016

如何将此存储在以服务为键,总金额为值的字典中?我刚刚开始学习Python,我很困惑大声笑。

1 个答案:

答案 0 :(得分:0)

您可以在此处使用collections.defaultdict()

from collections import defaultdict

with open('file') as f: # open file in read only mode
    my_dict = defaultdict(float)  # will hold default value as 0.0 for any key
    for line in f.readlines():  # iterate over each line
        _, key, val, _ = line.split(';') # split line on ';' and take 1 & 2 index
        my_dict[key] += val  # add amount to service