简体   繁体   English

将Python OrderedDict写入CSV

[英]Write Python OrderedDict to CSV

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. 我需要将有序字典的内容解析为CSV格式,第一行中的键和第二行中的键值。 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)]) . OrderedDict中的值是您所期望的(看起来像在终端中打印出来的): ([(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)

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

Thanks in advance for your help! 在此先感谢您的帮助!

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. 如建议的那样,我正在与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. 但是,在我这样做的过程中,我想到无需学习Pandas模块的来龙去脉就可以做到这一点。 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. Create two empty lists corresponding to the keys and values in my ordered dictionary 在我的有序字典中创建两个与键和值对应的空列表

  2. 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 由于Python中的列表保持顺序,因此可以确保两个列表中的相应索引项都属于同一列

  3. Write the keys to the first row of my CSV, and the values to the second 将密钥写入CSV的第一行,并将值写入第二行

I'm sure there are more elegant ways to do this, but this is is sufficient for my purposes. 我敢肯定有更优雅的方法可以做到这一点,但这足以满足我的目的。

As of Python 3.7 dictionaries retain order so you can just use dict() to turn an ordered dictionary into a usable dictionary. 从Python 3.7开始,字典保留顺序,因此您只需使用dict()即可将有序字典变成可用字典。

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

Reading/Writing out a dictionary to csv file in python 在python中读/写字典到csv文件

Shows how to write Dict using Pandas. 显示如何使用熊猫编写Dict。

import pandas as pd

d = {
   'a': (1, 101),
   'b': (2, 202),
   'c': (3, 303)
}
pd.DataFrame.from_dict(d, orient="index").to_csv("dict.csv")

Here is another, more general solution assuming you don't have a list of rows (maybe they don't fit in memory) or a copy of the headers (maybe the write_csv function is generic): 这是另一个更通用的解决方案,假设您没有行列表(也许它们不适合内存)或标头的副本(也许write_csv函数是通用的):

def gen_rows():
    yield OrderedDict(a=1, b=2)

def write_csv():
    it = genrows()
    first_row = it.next()  # __next__ in py3
    with open("frequencies.csv", "w") as outfile:
        wr = csv.DictWriter(outfile, fieldnames=list(first_row))
        wr.writeheader()
        wr.writerow(first_row)
        wr.writerows(it)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM