2

I have a dictionary which looks like:

dict = {'a':[1,2,3],
   'b':[4,5,6],
   'c':[7,8,9]}

I want to write each array into a column in a file, such that the output looks like:

1 4 7
2 5 6
3 6 9

where values are tab separated. So far I have tried:

import csv
with open('text.csv', 'w') as f:
    writer = csv.writer(f, delimiter='\t')
    for k,array in dict.items():
        writer.writerows(zip(array))

But this just prints numbers 1 to 9 in a single column. Can someone help me with this?

(Is there any more efficient way to store multiple arrays like shown in the dictionary such that it becomes easier to write on a file?)

blhsing
  • 91,368
  • 6
  • 71
  • 106
ruskin23
  • 145
  • 1
  • 10
  • https://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file This might help you with writing a dictionary from a csv. – Joey Feb 21 '19 at 23:57

3 Answers3

2

You can use zip after unpacking the dict values:

with open('text.csv', 'w') as f:
    writer = csv.writer(f, delimiter='\t')
    writer.writerows(zip(*d.values()))
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

You can modify from here and then write the output to the file. I'm sure there are cleaner ways to do it, but this does what you're asking. Though this assumes the rows are all the same length. If all columns don't have data, this will not produce the desired output.

# data in
dict = {'a':[1,2,3],
   'b':[4,5,6],
   'c':[7,8,9]}


cols = []


for k, v in dict.items():
    cur_col = 0
    for i in v:
        try:
            cols[cur_col].append(str(i))
            cur_col += 1
        except IndexError as e:
            cols.append([str(i)])
            cur_col +=1
    cur_col = 0

for row in cols:
    print("\t".join(row))

Output:

1   4   7
2   5   8
3   6   9
Dave
  • 592
  • 3
  • 15
0

If you are open to using pandas, it's fairly straightforward. I would also suggest not using dict as a variable name since it's a builtin function.

import pandas as pd

arr_dict = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}
pd.DataFrame(arr_dict).to_csv('test.csv', index=False, sep='\t')

If arrays are of different length, You'll have to be a bit more creative. Many examples are in this post with one of them here:

pd.DataFrame.from_dict(arr_dict, orient='index').T
busybear
  • 10,194
  • 1
  • 25
  • 42