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

2024-06-16 19:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Flask从一个HTML表单获取输入,该表单将其作为dictionary对象返回,例如:

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

因此,我可以在顶部有我的字段名,并创建一个好看的表。我怎样才能做到这一点?你知道吗


Tags: csv对象nameformflask表单dictionaryhtml
1条回答
网友
1楼 · 发布于 2024-06-16 19:33:36

假设您已经在使用Python的csv模块,如果您想要头文件,这里有一种长格式的方法。你知道吗

这个例子使用了^{},它是专门设计用来处理字典的。你知道吗

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提供的^{}类反序列化。你知道吗

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'}]

相关问题 更多 >