将Python OrderedDict写入CSV [英] Write Python OrderedDict to CSV

查看:261
本文介绍了将Python OrderedDict写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本有序的字典,正如人们所期望的那样,它包含许多键-值对.我需要将有序字典的内容解析为CSV格式,第一行中的键和第二行中的键值.我把第一行记下来了,但是我对如何写第二行不知所措. OrderedDict中的值是您所期望的(看起来像在终端中打印出来的):([(a, 1), (b, 2), (c, 3)]).这就是我所拥有的:

I have an ordered dictionary that, as one would expect, contains a number of key-value pairs. I need to parse the contents of the ordered dictionary into CSV format, with the keys in the top row and their respective values in the second row. I've got the first row down, but I'm at a loss as to how to write the second row. The values in the OrderedDict are what you'd expect (what it looks like printed out in the terminal): ([(a, 1), (b, 2), (c, 3)]). Here's what I have:

import csv
with open("frequencies.csv", "w") as outfile:
    csvwriter = csv.writer(outfile)
    csvwriter.writerow(myDict)

我尝试遍历值并将它们附加到列表中,但是列表没有保持有序字典的原始顺序,据我所知,这将使打印值非常困难从列表到CSV,以便它们与正确的键匹配.

I tried iterating over the values and appending them to a list, but the list didn't maintain the original order of the ordered dictionary, which, as far as I could tell, would have made it pretty difficult to print the values from the list to the CSV so that they'd match up with the correct keys.

提前感谢您的帮助!

推荐答案

好的,我将在这里回答我自己的问题.几个人很友善,可以在评论中提出建议.如建议的那样,我正在与Pandas一起完成此任务.但是,在我这样做的时候,我想到无需学习Pandas模块的来龙去脉就可以做到这一点.这是我想出的:

Alright, I'm going to answer my own question here. A couple of people were kind enough to offer suggestions in the comments. As suggested, I was working on accomplishing this with Pandas. As I was doing so, however, it occurred to me that I could do this without having to learn the ins and outs of the Pandas module. Here's what I came up with:

import csv

keys, values = [], []

for key, value in myOrderedDict.items():
    keys.append(key)
    values.append(value)       

with open("frequencies.csv", "w") as outfile:
    csvwriter = csv.writer(outfile)
    csvwriter.writerow(keys)
    csvwriter.writerow(values)

所以这是这里发生的事情:

So here's what's going on here:

  1. 在我的有序字典中创建两个与键和值相对应的空列表

  1. Create two empty lists corresponding to the keys and values in my ordered dictionary

遍历我的有序字典中的键/值对,并将每个对附加到其各自的列表.由于Python中的列表保持顺序,因此可以确保两个列表中相应索引的项都属于同一

Iterate over the key/value pairs in my ordered dictionary, appending each pair to its respective list. Because lists in Python retain their order, this ensures that items of corresponding indices in either list belong together

将键写入到CSV的第一行,并将值写入第二行

Write the keys to the first row of my CSV, and the values to the second

我敢肯定有更优雅的方法可以做到这一点,但这对我来说已经足够了.

I'm sure there are more elegant ways to do this, but this is is sufficient for my purposes.

这篇关于将Python OrderedDict写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆