[英]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
和zip_longest
执行此操作。
",".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. ",".join(abc.keys())
将返回第一行(键),如key1,key2
,然后用zip_longest (Python2.x使用izip_longest
)聚合elements.And用同样的方法追加,
和\\n
到字符串。
zip_longest 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.
如果可迭代项的长度不均匀,则将缺失值填充为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.