0

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
cuser
  • 432
  • 1
  • 5
  • 13
  • 2
    Using itertools.izip_longest? – Useless Jul 12 '18 at 11:35
  • @Useless Yep, that's a solution. But, aren't there any other direct ways to achieve this? – cuser Jul 12 '18 at 11:45
  • 1
    You're currently calling `zip`. You can change this to `itertools.izip_longest`. How many other ways do you want to achieve the same thing? You can easily write a loop explicitly, or write your own equivalent version of `izip_longest`, but ... why do you want to? – Useless Jul 12 '18 at 11:57

1 Answers1

2

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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113