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!
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:
Create two empty lists corresponding to the keys and values in my ordered dictionary
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
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.