Creating a dictionary from a csv file?

后端 未结 16 2077
北荒
北荒 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: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()
    

提交回复
热议问题