Dictionary to CSV file: ordering columns

I am trying to export a list of dictionaries to a .csv file:

keys = hist[0].keys()
with open(file, 'wt') as output_file:
    dict_writer = csv.DictWriter(output_file, keys, lineterminator='\n')
    dict_writer.writeheader()
    dict_writer.writerows(hist)

      

I want the last key in the dictionary to be the first key in the column.

My list of dictionaries (hist):

[{'RSD': '-', 'GBP': '0.500409', 'Date': '2008-04-05'}, 
 {'RSD': '-', 'GBP': '0.500409', 'Date': '2008-04-06'}, 
 {'RSD': '-', 'GBP': '0.50331', 'Date': '2008-04-07'}, 
 {'RSD': '-', 'GBP': '0.507939', 'Date': '2008-04-08'},
...

      

What I got:

for x in dates:
    l = {}
    for y in currs:
        try:
            m = exrates.get_exrates(x)[y]
        except KeyError:
            m = '-'
        l[y] = m
    l['Date'] = x
    hist.append(l)

      

How do I reorder or reorder columns?

+3


source to share


3 answers


Use OrderedDict if you want to order and reverse:

from collections import OrderedDict

for x in dates:
    l = OrderedDict()
    for y in currs:
        try:
            m = exrates.get_exrates(x)[y]
        except KeyError:
            m = '-'
        l[y] = m
    l['Date'] = x
    hist.append(l)

      

To reverse the order, use the reverse:

keys = list(reversed(list(hist[0].keys())))
print(keys)

      

If you just want to have the last key in front:

k = list(hist[0].keys())

keys = keys[-1] +  key[:-1]
print(keys)

      



You can also use comprehension with dict.get

:

for x in dates:
    l = OrderedDict((y, exrates.get_exrates(x).get(y, "-")) for y in currs)
    l['Date'] = x
    hist.append(l)

      

If you are going to supply headers and don't want orderly dictaphones after you just write as you go, assuming curr is a list, you can use curr as a header adding Date:

import csv

with open(file, 'wt') as output_file:
    wr = csv.writer(output_file)
    wr.writerow(["Date"] + currs)
    for x in dates:
        row = [x] + [exrates.get_exrates(x).get(y, "-") for y in currs]
        wr.writerow(row)

      

The items in the activity are what you use as keys, which are your headers, so saving the dicts is not required if all you want to do is write the content [exrates.get_exrates(x).get(y, "-") for y in currs]

from x

that written to the first column in the Date section.

+3


source


Hardcode the header with the desired order.

keys = ['Date', 'RSD', 'GBP']
with open(file, 'wt') as output_file:
    dict_writer = csv.DictWriter(output_file, keys, lineterminator='\n')
    dict_writer.writeheader()
    dict_writer.writerows(hist)

      



hardcoding is preferred anytime you want your csv to be in a specific format.

+5


source


(If you don't mind using pandas

), you can do this by simply reordering the columns, look at the last step:

In [1]: import pandas as pd

In [2]: x = [{'RSD': '-', 'GBP': '0.500409', 'Date': '2008-04-05'}, 
   ...:  {'RSD': '-', 'GBP': '0.500409', 'Date': '2008-04-06'}, 
   ...:  {'RSD': '-', 'GBP': '0.50331', 'Date': '2008-04-07'}, 
   ...:  {'RSD': '-', 'GBP': '0.507939', 'Date': '2008-04-08'},]

In [3]: pd.DataFrame(x)
Out[3]: 
         Date       GBP RSD
0  2008-04-05  0.500409   -
1  2008-04-06  0.500409   -
2  2008-04-07   0.50331   -
3  2008-04-08  0.507939   -

In [4]: y = pd.DataFrame(x)

In [5]: y = y[['RSD', 'GBP', 'Date']]

In [6]: y
Out[6]: 
  RSD       GBP        Date
0   -  0.500409  2008-04-05
1   -  0.500409  2008-04-06
2   -   0.50331  2008-04-07
3   -  0.507939  2008-04-08

      

+1


source







All Articles