Reading/Writing out a dictionary to csv file in python

后端 未结 3 654
灰色年华
灰色年华 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:50

    I didn't find enough benefit to use Pandas here since the problem is simple.

    Also note to OP, if you want to store values to a file just for reading it back simply use JSON or Python's shelve module. Exporting to CSV should be minimised only when we need to interact potentially Excel users.

    The below code converts a dict into CSV

    value1 = 'one'
    value2 = 'two'
    d = { 
            'key1': (value1, value2), 
            'key2': (value1, value2), 
            'key3': (value1, value2)
        }
    CSV ="\n".join([k+','+','.join(v) for k,v in d.items()]) 
    #You can store this CSV string variable to file as below
    # with open("filename.csv", "w") as file:
        # file.write(CSV)
    

    This code explains what happens inside the list comprehension.

    CSV = ""
    for k,v in d.items():
        line = "{},{}\n".format(k, ",".join(v))
        CSV+=line
    print CSV 
    

提交回复
热议问题