将字典数据导出到csv文件

时间:2018-07-24 14:46:03

标签: python python-3.x

我已经在Python中创建了一个字典数据类型:

selecteddatas = random.sample(numbers, 100)
    for data in selecteddatas:
        calls = random.choice(range(600))
        a[data] = {'time_stamp': str_now, 'calls': calls}

,并且我正在尝试将其导出到csv文件,但无法正常工作。谁能建议我该怎么做。

2 个答案:

答案 0 :(得分:0)

具有相同键的字典列表可以轻松转换为pandas DataFrame。然后可以将它们轻松转换为csv。

import pandas as pd
pd.DataFrame(a).to_csv(filepath,index=False)

答案 1 :(得分:0)

在没有pandas的情况下,使用csv.DictWriter

import random, csv, datetime

selecteddatas = random.sample(list(range(100)), 100)
a = {}
for data in selecteddatas:
    calls = random.choice(range(600))
    a[data] = {'time_stamp': datetime.datetime.now(), 'calls': calls}

with open('data.csv', 'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=['time_stamp', 'calls'])

    writer.writeheader()
    for k in a.keys():
        writer.writerow(a[k])

data.csv包含:

time_stamp,calls
2018-07-24 17:54:01.989054,273
2018-07-24 17:54:01.989059,290
2018-07-24 17:54:01.989062,51
2018-07-24 17:54:01.989064,188
2018-07-24 17:54:01.989067,518
...and so on.