Write dictionary of lists to a CSV file

后端 未结 6 924
星月不相逢
星月不相逢 2020-12-01 08:01

I\'m struggling with writing a dictionary of lists to a .csv file.

This is how my dictionary looks like:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[k         


        
6条回答
  •  情深已故
    2020-12-01 08:14

    If you don't care about the order of your columns (since dictionaries are unordered), you can simply use zip():

    d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
    with open("test.csv", "wb") as outfile:
       writer = csv.writer(outfile)
       writer.writerow(d.keys())
       writer.writerows(zip(*d.values()))
    

    Result:

    key3    key2    key1
    7       4       1
    8       5       2
    9       6       3
    

    If you do care about order, you need to sort the keys:

    keys = sorted(d.keys())
    with open("test.csv", "wb") as outfile:
       writer = csv.writer(outfile, delimiter = "\t")
       writer.writerow(keys)
       writer.writerows(zip(*[d[key] for key in keys]))
    

    Result:

    key1    key2    key3
    1       4       7
    2       5       8
    3       6       9
    

提交回复
热议问题