Creating a dictionary from a csv file?

后端 未结 16 2051
北荒
北荒 2020-11-22 06:13

I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file rep

16条回答
  •  粉色の甜心
    2020-11-22 06:19

    Try to use a defaultdict and DictReader.

    import csv
    from collections import defaultdict
    my_dict = defaultdict(list)
    
    with open('filename.csv', 'r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for line in csv_reader:
            for key, value in line.items():
                my_dict[key].append(value)
    

    It returns:

    {'key1':[value_1, value_2, value_3], 'key2': [value_a, value_b, value_c], 'Key3':[value_x, Value_y, Value_z]}
    

提交回复
热议问题