将多列csv文件读取到嵌套字典

时间:2019-02-22 21:56:56

标签: 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 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'])

1 个答案:

答案 0 :(得分:2)

您可以改用export

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']) 变为:

symbols

或者,如果您更喜欢使用{'Advanced': {'AAA': ['30 secs', '60 secs'], 'BBB': ['30 secs']}, 'Basic': {'CCC': ['30 secs', '60 secs'], 'DDD': ['30 secs']}} ,则应将collections.defaultdict设为列表symbols中的defaultdict

defaultdict