R_Est
R_Est

Reputation: 13

Python: Write dictionary lists with different indexes to CSV file

I have a dictionary of lists in which some lists only have one value while the others have many.

Using this code, I get the output I intend:

    import csv
    from collections import OrderedDict

    my_dict = OrderedDict()
    my_dict["Header1"] = [1,2,3]
    my_dict["Header2"] = [4,5,6]

    #if file doesn't exist...
    with open('mycsv.csv', 'wb') as f:
        w = csv.writer(f, delimiter=';')
        w.writerow(my_dict.keys())
    with open('mycsv.csv', 'ab') as f:
        w = csv.writer(f, delimiter=';')
        w.writerows(zip(*my_dict.values()))

Which will look somewhat like:

Header1;Header2

1;4

2;5

3;6

But in my case, when I have a dictionary of lists of this sort:

    my_dict["Header1"] = [1,2,3]
    my_dict["Header2"] = [4]

I get an output like:

Header1;Header2

1;4

When I intended to have:

Header1;Header2

1;4

2;

3;

Any suggestions on how to solve this?

Thank you in advance (and sorry for any bad thread formatting,it's my first question here :P)!

Upvotes: 1

Views: 63

Answers (1)

kardaj
kardaj

Reputation: 1935

You can use map(lambda *x: tuple(x), *my_dict.values()) instead of zip. This will replace empty elements with None, or you can use itertools.izip_longest(*my_dict.values()). csv will automatically leave None values empty.

Upvotes: 1

Related Questions