Write dictionary of lists to a CSV file

后端 未结 6 942
星月不相逢
星月不相逢 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:22

    This will work even when the list in key are of different length.

        with myFile:  
            writer = csv.DictWriter(myFile, fieldnames=list(clusterWordMap.keys()))   
            writer.writeheader()
            while True:
                data={}
                for key in clusterWordMap:
                    try:
                        data[key] = clusterWordMap[key][ind]
                    except:
                        pass
                if not data:
                    break
                writer.writerow(data)
    

    You can use pandas for saving it into csv:

    df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
    df.to_csv(filename, encoding='utf-8', index=False)
    

提交回复
热议问题