字典到CSV文件:列

时间:2015-04-27 17:42:20

标签: python list csv dictionary

我正在尝试将字典列表导出到.csv文件:

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)

我希望字典中的最后一个键是列中的第一个键。

我的词典列表(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'},
...

我得到了:

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)

如何更改字典的顺序或更改列的顺序?

3 个答案:

答案 0 :(得分:5)

使用您想要的顺序对标题进行硬编码。

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)

如果您希望csv具有特定格式,则首选硬编码。

答案 1 :(得分:3)

如果您想要订购和反向,请使用OrderedDict:

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)

要获得相反的顺序,请使用reverse:

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

如果你只想把最后一把钥匙放在前面:

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

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

您还可以使用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)

如果您打算提供标题,并且在写完之后不想要有序的dicts,假设curr是一个列表,您可以使用curr作为标题添加日期:

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)

curr中的元素是您用作标题的键,因此如果您只想写[exrates.get_exrates(x).get(y, "-") for y in currs]的内容x,则不需要存储dicts。日期下的第一栏。

答案 2 :(得分:1)

(如果你不反对使用pandas)你可以通过简单地重新排序列来做到这一点,看看最后一步:

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