Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Thanks in advance for your help!

like image 396
jguberman Avatar asked Dec 01 '16 03:12

jguberman


People also ask

How do I save a dictionary to csv?

In Python to convert a dictionary to CSV use the dictwriter() method. This method is used to insert data into the CSV file. In Python, the CSV module stores the dictwriter() method. It creates an object and works like the dictwriter().

How do I convert a list into a CSV file in Python?

To convert a list of lists to csv in python, we can use the csv. writer() method along with the csv. writerow() method.

How do I append to a CSV file?

If you need to append row(s) to a CSV file, replace the write mode ( w ) with append mode ( a ) and skip writing the column names as a row ( writer. writerow(column_name) ).

How to write Python dictionary in CSV file using csvwriter?

DictWriter. writeheader () is used to write a row of column headings / field names to the given CSV file csvwriter. writerows () method is used to write rows of data into the specified file. Note: To write a single dictionary in CSV file use writerow () method Complete code to write python dictionaries in CSV file

How to open a CSV file in Python?

In Python, a CSV file is a file that contains values break by newline and commas. By using CSV.writer.writerow () we can convert to dictionary into a CSV file. To give a path of a CSV file we can apply the open () file method. In this method, we have passed the ‘w’ keyword as an argument that means to open a stream of a CSV file for writing mode.

How to write the first line in a CSV file?

Now if we want to open a file in the writing mode then we can use the open () function and write the first line in the CSV file we use the writerheader () method. In this example, the writerow () function is to write the row argument to the writer’s file object.

How do I convert a CSV file to a string?

In Python, the CSVwriter () method helps the user to convert the user data into a string. In this example, the script writes data into the ‘test8.Csv’ file and the writerow () method writes a row of data into the given file and passes ‘new_key’ and ‘new_val’ keywords as an argument.


2 Answers

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)
like image 90
eddygeek Avatar answered Oct 05 '22 16:10

eddygeek


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.

like image 21
jguberman Avatar answered Oct 05 '22 18:10

jguberman