Creating a dictionary from a csv file?

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

提交回复
热议问题