Reading/Writing out a dictionary to csv file in python

后端 未结 3 679
灰色年华
灰色年华 2021-02-05 17:14

Pretty new to python, and the documentation for csv files is a bit confusing.

I have a dictionary that looks like the following:

key1: (value1, value2)

         


        
3条回答
  •  春和景丽
    2021-02-05 17:53

    I highly recommend Pandas for this.

    Convert to Pandas DataFrame:

    import pandas as pd
    
    d = {
        'a': (1, 101),
        'b': (2, 202),
        'c': (3, 303)
    }
    df = pd.DataFrame.from_dict(d, orient="index")
    

    Create a CSV file:

    df.to_csv("data.csv")
    

    Read the CSV file back as a DataFrame:

    df = pd.read_csv("data.csv", index_col=0)
    

    Convert the DataFrame back to the original dictionary format:

    d = df.to_dict("split")
    d = dict(zip(d["index"], d["data"]))
    

    EDIT: Since you mention that your goal to use the output file in Excel, Pandas to_excel() and read_excel() might be more useful to you since they better-preserve the content between conversions. Also, you might want skip Excel altogether and use the standard Python scientific stack.

提交回复
热议问题