Creating a dictionary from a csv file?

后端 未结 16 2056
北荒
北荒 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.

提交回复
热议问题