在python中要dict的文本文件?

2024-06-06 22:42:35 发布

您现在位置: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

如何将其存储在一个以服务为键、总额为值的dict中?我刚刚开始学习Python,我很困惑,哈哈


Tags: frankevedictbobdavid文本文件alicecharles
1条回答
网友
1楼 · 发布于 2024-06-06 22:42:35

您可以在此处使用^{}

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

相关问题 更多 >