Outputting a Python dictionary with values in an array to a CSV file.

回眸只為那壹抹淺笑 提交于 2019-12-11 10:13:04

问题


First question here, please forgive the various and sundry errors I'm sure to make.

I've been working on this for awhile, and I admit to being stumped - dictionaries in a general sense make my head hurt a bit, as my background is more on the statistical side, where data has pretty explicit structure. I'm working in Python 2.7, and I've got the following problem: At the end of some analysis, using the NetworkX package, I've got two dictionaries I'm interested in, which I'll call Able and Baker.

Each is essentially a dictionary of a network node's name, and a value. So something like:

Joe : 7 Kate: 9 Mike: 3 -and- Joe: 12 Kate: 4 Mike: 2

But this output is going to leave Python, and while I could output the whole thing as two separate files fairly easily (and have been up until now), it would be really nice to have it come out as a single CSV file, formatted like so:

Joe, 7, 12
Kate, 9, 4
Mike, 3, 2

Right now, I'm running the following to get the two dictionaries combined into a single dictionary:

output = dict((k, [Able[k], Baker.get(k)]) for k in Able)
output.update((k, [None, Baker[k]]) for k in Baker if k not in Able)

This gets me close to what I want, namely a dictionary with Joe: [7, 12]. But I'm honestly stumped as to how to get CSV writer to cooperate and output the [7,12] as distinct entities (i.e. 7,12) rather than as parts of an array. The closest I've gotten is:

net_out = open('output.csv', 'w')
writer = csv.writer(net_out, dialect='excel')
for node, value in output.items():
    writer.writerow([node,value])
net_out.close()

Which puts out rows of Joe, [7,12]. Anyone able to point me in the right direction?


回答1:


You're passing a list containing a name and a list with two numbers to writer.writerow. To get what you want, flatten the list into just a list of the name and numbers. Simple approach:

for node, value in output.items():
    writer.writerow([node] + value)



回答2:


Replace writer.writerow([node,value]) with writer.writerow([node]+value)



来源:https://stackoverflow.com/questions/6870103/outputting-a-python-dictionary-with-values-in-an-array-to-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!