Creating a dictionary from a csv file?

后端 未结 16 2363
北荒
北荒 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:36

    For simple csv files, such as the following

    id,col1,col2,col3
    row1,r1c1,r1c2,r1c3
    row2,r2c1,r2c2,r2c3
    row3,r3c1,r3c2,r3c3
    row4,r4c1,r4c2,r4c3
    

    You can convert it to a Python dictionary using only built-ins

    with open(csv_file) as f:
        csv_list = [[val.strip() for val in r.split(",")] for r in f.readlines()]
    
    (_, *header), *data = csv_list
    csv_dict = {}
    for row in data:
        key, *values = row   
        csv_dict[key] = {key: value for key, value in zip(header, values)}
    

    This should yield the following dictionary

    {'row1': {'col1': 'r1c1', 'col2': 'r1c2', 'col3': 'r1c3'},
     'row2': {'col1': 'r2c1', 'col2': 'r2c2', 'col3': 'r2c3'},
     'row3': {'col1': 'r3c1', 'col2': 'r3c2', 'col3': 'r3c3'},
     'row4': {'col1': 'r4c1', 'col2': 'r4c2', 'col3': 'r4c3'}}
    

    Note: Python dictionaries have unique keys, so if your csv file has duplicate ids you should append each row to a list.

    for row in data:
        key, *values = row
    
        if key not in csv_dict:
                csv_dict[key] = []
    
        csv_dict[key].append({key: value for key, value in zip(header, values)})
    

提交回复
热议问题