如何在Python中将字典转换为列表

时间:2017-12-06 17:43:35

标签: python csv

我使用Flask从HTML表单中获取输入,然后将其作为字典对象返回,例如:

form = {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'}

现在,我可以使用dict.items()将字典转换为可以在HTML表格中显示的格式(元组列表):

formList = [('Name', Eddie), ('Comment', 'Nice Location'), ('Days Stayed', '7')]

通过以下方式很好地存储到.csv中:

Name,['Eddie']
Comment,['Nice Location']
Days Stayed,['7']

但是,我希望我的.csv(以及HTML表格)能像这样存储:

Eddie, Nice Location, 7
Dave, Good Food, 14
Steve, Room was cosy, 10

所以我可以将我的字段名称放在顶部并创建一个漂亮的表格。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

假设您已经在使用Python的csv模块,如果您需要标题,这里有一种很长的方法。

此示例使用专门用于处理词典的DictWriter

import csv

form_data = [
    {'Name': 'Eddie', 'Comment': 'Nice location', 'Days Stayed': '7'},
    {'Name': 'Dave', 'Comment': 'Good Food', 'Days Stayed': '14'},
    {'Name': 'Steve', 'Comment': 'Room was cosy', 'Days Stayed': '10'}
]

with open('output.csv', 'w') as csvfile:
    # this defines the fields you want from dictionaries
    # you pass to the writer, and the order in which they should
    # be emitted in the resulting CSV
    fields = ['Name', 'Comment', 'Days Stayed']
    dw = csv.DictWriter(csvfile, fieldnames)

    # omit this if you don't want a header written
    dw.writeheader()
    for row in form_data:
        dw.writerow(row)

结果output.csv看起来像这样:

Name,Comment,Days Stayed
Eddie,Nice location,7
Dave,Good Food,14
Steve,Room was cosy,10

您可以使用csv提供的DictReader类同样反序列化。

import csv

rows = None
with open('output.csv') as csvfile:
    fields = ['Name', 'Comment', 'Days Stayed']
    reader = csv.DictReader(csvfile)
    rows = [row for row in reader]

rows将如下所示:

[{'Comment': 'Nice location', 'Days Stayed': '7', 'Name': 'Eddie'},
 {'Comment': 'Good Food', 'Days Stayed': '14', 'Name': 'Dave'},
 {'Comment': 'Room was cosy', 'Days Stayed': '10', 'Name': 'Steve'}]