【发布时间】:2019-02-22 21:56:56
【问题描述】:
我正在尝试从 csv 文件中读取数据并将数据存储在嵌套字典中。
CSV file content
Type, ID, Frequency
Advanced,AAA,30 secs
Advanced,AAA,60 secs
Advanced,BBB,30 secs
Basic,CCC,30 secs
Basic,CCC,60 secs
Basic,DDD,30 secs
Expected output where the 'type' is the higher level key with the values as another dictionary with the ID and frequency as the key/value pair.
{'Advanced': {'AAA':['30 secs', '60 secs'], 'BBB':['30 secs']}, 'Basic': {'CCC':['30 secs', '60 secs'], 'DDD':['30 secs']}}
通过两列,我可以使用 defaultdict 容器来工作。
symbols = co.defaultdict(list)
with open(filename, 'r') as f:
lines = csv.DictReader(f)
for line in lines:
print(line)
symbols[line['Type']].append(line['ID'])
【问题讨论】:
标签: python dictionary