简体   繁体   English

如何将字典的关键字放在csv的第一行而不是第一列?

[英]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. 您可以使用joinzip_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.

相关问题 将 CSV 文件作为包含第一行作为标题(键)的字典读取 - Read CSV file as a dictionary containing first row as headers (keys) 将python字典写入CSV列:第一列的键,第二列的值 - Write python dictionary to CSV columns: keys to first column, values to second 带有第一行作为键的CSV文件 - Csv file with first row as keys 如何在将dict键设为第一列而不是索引的同时,从字典转到pandas DataFrame再到CSV - How to go from dictionary to pandas DataFrame to CSV while making the dict keys the first column, not the index Pandas CSV 和标题 - CSV 将第一行作为实际 Z099FB995346F31C749F6E40DB0FZ59 导入。 如果添加 header,它会覆盖而不是插入? - Pandas CSV and Headers - CSV imports first row as actual header. If add a header, it overwrites rather than inserts? 为什么将 numpy 数组转换为 csv 文件不显示属性名称,而是将第一行值作为属性名称? - why converting numpy array into csv file show no attributes name but rather put the first row values as the attribute names? Python:CSV 按列而不是行写入 - Python: CSV write by column rather than row 如何使用csv使Python读取一行中的第一个单词而不是第一个字符? - How can I make Python using csv read the first word in a line rather than the first character? 如何返回字典的前 4 个键? - How to return the first 4 keys of a dictionary? 如何使用第一行作为键的csv文件创建dict - How to create dict using csv file with first row as keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM