文本文件包含有关课后活动(姓名,每月价格,日期和时间)的信息,如下所示:
Swimming,20,Monday,15,Monday,17,Wednesday,18,Friday,15
Football,20,Tuesday,18,Wednesday,17,Wednesday,18,Thursday,19
Ballet,40,Monday,18,Tuesday,18,Wednesday,16,Thursday,16,Friday,17
为了表示课程目录,我创建了一个嵌套字典,格式如下:
{'Swimming': {'Price': '20', 'Dates': {'Monday': ['15', '17'], 'Wednesday': ['18'], 'Friday': ['15']}}, 'Football': {'Price': '20', 'Dates': {'Tuesday': ['18'], 'Wednesday': ['17', '18'], 'Thursday': ['19']}}, 'Ballet': {'Price': '40', 'Dates': {'Monday': ['18'], 'Tuesday': ['18'], 'Wednesday': ['16'], 'Thursday': ['16'], 'Friday': ['17']}}}
代码如下:
with open("fil.txt", "r") as f:
catalogue = {}
while True:
content = f.readline().strip()
if not content: break
content = content.split(',')
u[content[0]] = {}
u[content[0]]['Price'] = content[1]
u[content[0]]['Dates'] = {}
for i in range(2,len(content),2):
if content[i] in u[content[0]]['Dates']:
u[content[0]]['Dates'][content[i]].append(content[i+1])
else:
u[content[0]]['Dates'][content[i]] = [content[i+1]]
我的问题是:有没有更简单的方法来实现这样的字典?或者也许应该使用另一个数据结构来表示目录而不是这个?
答案 0 :(得分:0)
这是通过collections.defaultdict
使用嵌套字典结构的一种方式。
from collections import defaultdict
u = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
with open("fil.txt", "r") as f:
catalogue = {}
while True:
content = f.readline().strip()
if not content: break
content = content.split(',')
u[content[0]]['Price'] = content[1]
for i in range(2,len(content),2):
u[content[0]]['Dates'][content[i]].append(content[i+1])
答案 1 :(得分:0)
我只想写一堂课。
%Y-%m-%d%H:%M:%S