Python 将多列csv文件读取到嵌套字典
我试图从csv文件中读取数据并将其存储在嵌套字典中Python 将多列csv文件读取到嵌套字典,python,dictionary,Python,Dictionary,我试图从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 va
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'])
您可以改用
dict.setdefault
:
symbols = {}
with open(filename, 'r') as f:
for row in csv.DictReader(f, skipinitialspace=True):
symbols.setdefault(row['Type'], {}).setdefault(row['ID'], []).append(row['Frequency'])
符号
变为:
{'Advanced': {'AAA': ['30 secs', '60 secs'], 'BBB': ['30 secs']}, 'Basic': {'CCC': ['30 secs', '60 secs'], 'DDD': ['30 secs']}}
或者,如果您更喜欢使用集合.defaultdict
,则应将符号
adefaultdict
改为列表的defaultdict
:
symbols = defaultdict(lambda: defaultdict(list))
for row in csv.DictReader(f, skipinitialspace=True):
symbols[row['Type']][row['ID']].append(row['Frequency'])