Best way to convert csv data to dict

后端 未结 4 1740
眼角桃花
眼角桃花 2021-01-03 22:07

I have csv file with following data

val1,val2,val3
1,2,3
22,23,33

So how can I convert data into dict

dict1 = { \'val1\': 1         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 22:33

    Oftentimes I feel like upgrading to pandas while manipulating CSVs. It gives you a whole new world of possibilities.

    import pandas as pd
    df=pd.read_csv('test.csv')
    for index, row in df.iterrows():
        d=row.to_dict()
        print(d)
    
    print("")
    
    print( df[df.val3>10].iloc[0].to_dict() )
    print( list(df[['val3']]['val3']) )
    

    Output:

    {'val1': 1, 'val2': 2, 'val3': 3}
    {'val1': 22, 'val2': 23, 'val3': 33}
    
    {'val1': 22, 'val2': 23, 'val3': 33}
    [3, 33]
    

提交回复
热议问题