Python: 如何从字典列表中创建一个csv字符串(而非文件)?

5
在Python中我有一个像这样的字典列表:
[
    {
        "col2": "2",
        "id": "1",
        "col3": "3",
        "col1": "1"
    },
    {
        "col2": "4",
        "id": "2",
        "col3": "6",
        "col1": "2"
    },
    {
        "col1": "1",
        "col2": "4",
        "id": "3",
        "col3": "7"
    }
]

我需要将其转换为包括标题行的csv格式字符串。(首先让我们不关心列和行分隔符...)因此,理想情况下结果应为:

id,col1,col2,col3
1,1,2,3
2,2,4,6
3,1,4,7

("ideally"是因为列的顺序并不重要;虽然最好将"id"列放在第一位...)
我在SOF上搜索过,有许多类似的问题,但答案总是涉及使用csv.DictWriter创建csv文件。我不想创建文件,我只想得到那个字符串!
当然,我可以循环遍历列表,在此循环内再循环遍历字典键,并以这种方式使用字符串操作创建csv字符串。但肯定有更简洁、更有效的方法来做到这一点吧?
此外,我知道Pandas库,但我正在尝试在非常受限制的环境中完成此操作,而我更愿意仅使用内置模块。
4个回答

7
你可以使用 io.StringIO 将数据写入 '字符串' 而不是文件。例如,对于 csv.DictWriter,我们可以使用以下代码:
import csv
import io

data = [...]  # your list of dicts

with io.StringIO() as csvfile:
    fieldnames = ['id', 'col1', 'col2', 'col3']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for row in data:
        writer.writerow(row)
    print(csvfile.getvalue())

3

最简单的方法是使用pandas:

import pandas as pd
df = pd.DataFrame.from_dict(your_list_of_dicts)
print(df.to_csv(index=False))

结果:

col1,col2,col3,id
1,2,3,1
2,4,6,2
1,4,7,3

如果您想重新排序列,那没问题:

col_order = ['id', 'col1', 'col2', 'col3']
df[col_order].to_csv(index=False)

或者,只需确保id列是第一列:

df.set_index('id', inplace=True) # the index is always printed first
df.to_csv() # leave the index to True this time

“pandas” 对于如此微不足道的任务来说是一个相当沉重的依赖。 - user2390182

2

具备内置功能:

from collections import OrderedDict

ord_d = OrderedDict().fromkeys(('id', 'col1', 'col2', 'col3'))
s = ','.join(ord_d.keys()) + '\n'
for d in lst:
    ord_d.update(d)
    s += ','.join(ord_d.values()) + '\n'

print(s)

输出结果:
id,col1,col2,col3
1,1,2,3
2,2,4,6
3,1,4,7

0

思路是获取所有可能的键和所有的值。 假设数据是您拥有的字典列表。 这应该可以工作:

output = ''
all_keys = set().union(*(d.keys() for d in data))
output += ",".split(all_keys) + '\n'
for item in data:
    item_str = ",".split([data[key] for key in all_keys if key in data else ''])
    output += item_str + '\n'

来源


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接