Write Python OrderedDict to CSV

a 夏天 提交于 2019-12-01 17:57:26

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. 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

  3. 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.

As of Python 3.7 dictionaries retain order so you can just use dict() to turn an ordered dictionary into a usable dictionary.

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

Shows how to write Dict using Pandas.

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):

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