Creating a dictionary from a csv file?

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

    If you have:

    1. Only 1 key and 1 value as key,value in your csv
    2. Do not want to import other packages
    3. Want to create a dict in one shot

    Do this:

    mydict = {y[0]: y[1] for y in [x.split(",") for x in open('file.csv').read().split('\n') if x]}
    

    What does it do?

    It uses list comprehension to split lines and the last "if x" is used to ignore blank line (usually at the end) which is then unpacked into a dict using dictionary comprehension.

    0 讨论(0)
  • 2020-11-22 06:15

    You have to just convert csv.reader to dict:

    ~ >> cat > 1.csv
    key1, value1
    key2, value2
    key2, value22
    key3, value3
    
    ~ >> cat > d.py
    import csv
    with open('1.csv') as f:
        d = dict(filter(None, csv.reader(f)))
    
    print(d)
    
    ~ >> python d.py
    {'key3': ' value3', 'key2': ' value22', 'key1': ' value1'}
    
    0 讨论(0)
  • 2020-11-22 06:16

    I believe the syntax you were looking for is as follows:

    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 = {rows[0]:rows[1] for rows in reader}
    

    Alternately, for python <= 2.7.1, you want:

    mydict = dict((rows[0],rows[1]) for rows in reader)
    
    0 讨论(0)
  • 2020-11-22 06:18

    You can also use numpy for this.

    from numpy import loadtxt
    key_value = loadtxt("filename.csv", delimiter=",")
    mydict = { k:v for k,v in key_value }
    
    0 讨论(0)
  • 2020-11-22 06:18

    Assuming you have a CSV of this structure:

    "a","b"
    1,2
    3,4
    5,6
    

    And you want the output to be:

    [{'a': '1', ' "b"': '2'}, {'a': '3', ' "b"': '4'}, {'a': '5', ' "b"': '6'}]
    

    A zip function (not yet mentioned) is simple and quite helpful.

    def read_csv(filename):
        with open(filename) as f:
            file_data=csv.reader(f)
            headers=next(file_data)
            return [dict(zip(headers,i)) for i in file_data]
    
    0 讨论(0)
  • 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]}
    
    0 讨论(0)
提交回复
热议问题