简体   繁体   中英

How to put keys of dictionary in first row of csv rather than first column?

keys = ['key1', 'key2', 'key3', 'key4']
list1 = ['a1', 'b3', 'c4', 'd2', 'h0', 'k1', 'p2', 'o3']
list2 = ['1', '2', '25', '23', '4', '5', '6', '210', '8', '02', '92', '320']


abc = dict(zip(keys[:4], [list1,list2]))

with open('myfilecsvs.csv', 'wb') as f:
    [f.write('{0},{1}\n'.format(key, value)) for key, value in abc.items()]

I am getting all keys in 1st column with this and values in other column respectively.

What I am trying to achieve is all keys in first row ie each key in specific column of first row and then their values below. Something like transpose

I willbe much grateful for your assist on this

You can use join and zip_longest to do this.

",".join(abc.keys()) will return first row (the keys) like key1,key2 ,and then use zip_longest (Python2.x use izip_longest ) to aggregate elements.And use the same way append , and \\n to the string.

zip_longest

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue.

from itertools import zip_longest

with open('myfilecsvs.csv', 'w') as f:
   f.write("\n".join([",".join(abc.keys()),*(",".join(i) for i in zip_longest(*abc.values(),fillvalue=''))]))

Output:

key1,key2
a1,1
b3,2
...
,02
,92
,320

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM