cuser
cuser

Reputation: 432

Saving a python dictionary (of lists) in a csv file

A python dictionary (of lists) can be saved in a CSV file as answered in the post available at Write dictionary of lists to a CSV file.

The answer is as follows (directly copied from the above post),

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()))

How can we achieve the same task when the lengths the of lists available in the dictionary are different as follows,

d = {"key1": [1,2,3], "key2": [5], "key3": [6,9]}

So that, it results in the following format (in the CSV),

  key1  key2  key3
   1     5     6
   2           9
   3

Upvotes: 0

Views: 489

Answers (1)

Rakesh
Rakesh

Reputation: 82795

If you can use pandas its very simple.

Demo:

import pandas as pd
d = {"key1": [1,2,3], "key2": [5], "key3": [6,9]}
df = pd.DataFrame.from_dict(d, orient='index')
df = df.transpose()
df.to_csv("test.csv", index=False)

Upvotes: 2

Related Questions