2016-11-06 46 views
0

我這是由這個文本文件:要在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,我很困惑。

回答

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