Creating a dictionary from a csv file?

后端 未结 16 2320
北荒
北荒 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: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'}
    

提交回复
热议问题