将字典写入csv,将键作为标题和值作为列 [英] Trouble writing a dictionary to csv with keys as headers and values as columns
问题描述
我有一个字典,如下所示:
mydict = {foo:[1,2],bar :[3,4],asdf:[5,6]}
尝试将其写入CSV文件,以使其类似于:
foo,bar,asdf
,5
2,4,6
我花了最后一小时寻找解决方案,我发现最近的一个建议做这样的事情:
headers = mydict.keys()
with open (File2.csv,w)as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(zip(mydict.values ))
这里写的是header,但不是值。 >
foo,bar,asdf
[1,2]
[3,4]
[5 ,6]
如何获得我需要的输出?谢谢
而不是 zip(mydict.values())
,使用 zip(* mydict.values())
。这里有区别:
>>> zip(mydict.values())
[([1,2],),([3,4],),([5,6],)]
>> zip(* mydict.values())
[(1,3,5),(2,4,6)]
基本上第二个版本和 zip([1,2],[3,4],[5,6])
。这在文档中称为拆封参数列表。 / p>
要强制执行排序,请使用以下命令:
> ; zip(*([k] + mydict [k] for k in sorted(mydict)))
[('asdf','bar','foo'),(5,3,1) ,4,2)]
这包括标题,因此只需将它传递给 writerows()
并删除 writerow()
调用头。
当然你可以为 sorted()
函数提供一个键
参数,以便进行任何排序。例如,为了确保与问题中的顺序相同:
>> order = {'foo':0,'bar':1,'asdf':2}
>>>> zip(*([k] + mydict [k] for k in sorted(mydict,key = order.get)))
[('foo','bar','asdf'), ,5),(2,4,6)]
I have a dictionary that looks like:
mydict = {"foo":[1,2], "bar":[3,4], "asdf":[5,6]}
I'm trying to write this to a CSV file so that it looks like:
foo,bar,asdf
1,3,5
2,4,6
I've spend the last hour looking for solutions, and the closest one I found suggested doing something like this:
headers = mydict.keys()
with open("File2.csv","w") as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(zip(mydict.values())
This writes the headers ok, but not the values. Here is my output:
foo,bar,asdf
[1,2]
[3,4]
[5,6]
How do I get to the output I need? I'd really appreciate some help. Thank you
Instead of zip(mydict.values())
, use zip(*mydict.values())
. Here is the difference:
>>> zip(mydict.values())
[([1, 2],), ([3, 4],), ([5, 6],)]
>>> zip(*mydict.values())
[(1, 3, 5), (2, 4, 6)]
Basically the second version does the same thing as zip([1, 2], [3, 4], [5, 6])
. This is called Unpacking Argument Lists in the docs.
To enforce a sort, use the following:
>>> zip(*([k] + mydict[k] for k in sorted(mydict)))
[('asdf', 'bar', 'foo'), (5, 3, 1), (6, 4, 2)]
This includes the headers, so just pass this into writerows()
and remove your writerow()
call for the headers.
Of course you can provide a key
argument to the sorted()
function there to do any sorting you like. For example to ensure the same order as you have in the question:
>>> order = {'foo': 0, 'bar': 1, 'asdf': 2}
>>> zip(*([k] + mydict[k] for k in sorted(mydict, key=order.get)))
[('foo', 'bar', 'asdf'), (1, 3, 5), (2, 4, 6)]
这篇关于将字典写入csv,将键作为标题和值作为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!