Dalvtor
Dalvtor

Reputation: 3286

Python dict to csv in columns format

I have the following dict

items = {'people': ['Peter', 'Danny'], 'numbers': [1,2,3,4], 'cities': ['London']}

And I would like to write that dict to a CSV file by columns, that is, with the following format:

people,numbers,cities
Peter,1,London
Danny,2,
     ,3,
     ,4,

My current approach won't work because I get the CSV file by rows:

people,Peter,Danny
numbers,1,2,3,4
cities,London

How can I do what I need?

Upvotes: 3

Views: 863

Answers (4)

ebonnal
ebonnal

Reputation: 1167

If you do not want to rely on external dependencies like pandas, you can quickly achieve this in pure python with join method of str objects.

items = {'people': ['Peter', 'Danny'],
         'numbers': [1, 2, 3, 4],
         'cities': ['London']}


def to_csv(items):
    # names of columns
    header = ','.join(list(items.keys()))
    # building lines
    lines = list()
    max_len = max([len(items[key]) for key in items.keys()])
    for i in range(max_len):
        lines.append(
            ','.join(
                [str(items[key][i]) for key in items.keys()
                 if i < len(items[key])]))
    # return header and lines separated by new lines
    return '\n'.join([header] + lines)


print(to_csv(items))

outputs :

people,numbers,cities
Peter,1,London
Danny,2,
,3,
,4,

Upvotes: 0

pault
pault

Reputation: 43524

A simple way is to calculate the length of the longest list in your dictionary, and then append '' to all the lists so they have this length.

num_rows = max((len(x) for x in items.values()))
items = {k: items[k] + [''] * (num_rows - len(items[k])) for k in items}
print(items)
#{'cities': ['London', '', '', ''],
# 'numbers': [1, 2, 3, 4],
# 'people': ['Peter', 'Danny', '', '']}

Then write the dict to csv using the csv module.

Or you can build a pandas DataFrame from your dictionary:

import pandas as pd
df = pd.DataFrame(items)
print(df)
#   cities  numbers people
#0  London        1  Peter
#1                2  Danny
#2                3       
#3                4       

Now you can write it to a file using the to_csv() method.

Upvotes: 0

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

Or you can use Pandas for that, which only takes two lines

import pandas as pd

pd.DataFrame(items).fillna('').to_csv('file_path')

Upvotes: 4

Ajax1234
Ajax1234

Reputation: 71461

You can use itertools.zip_longest (itertools.izip_longest in Python2):

from itertools import zip_longest
import csv
items = {'people': ['Peter', 'Danny'], 'numbers': [1,2,3,4], 'cities': ['London']}
headers = ['people', 'numbers', 'cities']
with open('filename.csv', 'w') as f:
  full_listing = [['' if not b else b for b in i] for i in zip_longest(*[items[c] for c in headers])]
  write = csv.writer(f)
  write.writerows([headers]+full_listing)

Output:

people,numbers,cities
Peter,1,London
Danny,2,
     ,3,
     ,4,

Upvotes: 4

Related Questions