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
3
  • 2
    Using itertools.izip_longest? Commented Jul 12, 2018 at 11:35
  • @Useless Yep, that's a solution. But, aren't there any other direct ways to achieve this? Commented Jul 12, 2018 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? Commented Jul 12, 2018 at 11:57

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.