Creating a dictionary from a csv file?

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

    You can use this, it is pretty cool:

    import dataconverters.commas as commas
    filename = 'test.csv'
    with open(filename) as f:
          records, metadata = commas.parse(f)
          for row in records:
                print 'this is row in dictionary:'+rowenter code here
    
    0 讨论(0)
  • 2020-11-22 06:22

    Open the file by calling open and then csv.DictReader.

    input_file = csv.DictReader(open("coors.csv"))
    

    You may iterate over the rows of the csv file dict reader object by iterating over input_file.

    for row in input_file:
        print(row)
    

    OR To access first line only

    dictobj = csv.DictReader(open('coors.csv')).next() 
    

    UPDATE In python 3+ versions, this code would change a little:

    reader = csv.DictReader(open('coors.csv'))
    dictobj = next(reader) 
    
    0 讨论(0)
  • 2020-11-22 06:27

    If you are OK with using the numpy package, then you can do something like the following:

    import numpy as np
    
    lines = np.genfromtxt("coors.csv", delimiter=",", dtype=None)
    my_dict = dict()
    for i in range(len(lines)):
       my_dict[lines[i][0]] = lines[i][1]
    
    0 讨论(0)
  • Many solutions have been posted and I'd like to contribute with mine, which works for a different number of columns in the CSV file. It creates a dictionary with one key per column, and the value for each key is a list with the elements in such column.

        input_file = csv.DictReader(open(path_to_csv_file))
        csv_dict = {elem: [] for elem in input_file.fieldnames}
        for row in input_file:
            for key in csv_dict.keys():
                csv_dict[key].append(row[key])
    
    0 讨论(0)
  • 2020-11-22 06:34

    This isn't elegant but a one line solution using pandas.

    import pandas as pd
    pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()
    

    If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):

    import pandas as pd
    pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
    
    0 讨论(0)
  • 2020-11-22 06:34

    I'd suggest adding if rows in case there is an empty line at the end of the file

    import csv
    with open('coors.csv', mode='r') as infile:
        reader = csv.reader(infile)
        with open('coors_new.csv', mode='w') as outfile:
            writer = csv.writer(outfile)
            mydict = dict(row[:2] for row in reader if row)
    
    0 讨论(0)
提交回复
热议问题