Creating a dictionary from a csv file?

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

    with pandas, it is much easier, for example. assuming you have the following data as CSV and let's call it test.txt / test.csv (you know CSV is a sort of text file )

    a,b,c,d
    1,2,3,4
    5,6,7,8
    

    now using pandas

    import pandas as pd
    df = pd.read_csv("./text.txt")
    df_to_doct = df.to_dict()
    

    for each row, it would be

    df.to_dict(orient='records')
    

    and that's it.

    0 讨论(0)
  • 2020-11-22 06:36
    import csv
    reader = csv.reader(open('filename.csv', 'r'))
    d = {}
    for row in reader:
       k, v = row
       d[k] = v
    
    0 讨论(0)
  • 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)})
    
    0 讨论(0)
  • 2020-11-22 06:37

    One-liner solution

    import pandas as pd
    
    dict = {row[0] : row[1] for _, row in pd.read_csv("file.csv").iterrows()}
    
    0 讨论(0)
提交回复
热议问题