繁体   English   中英

Python:将字典键转换为 csv 标题和值转换为行

[英]Python: Convert dictionary keys into csv headers and values into rows

嗨,互联网程序员,

我对编程相当陌生,我正在尝试将数据导出到 csv 但 json 上有一个字段 api 返回的字段是包含多个字典的列表。

这是该字段的样子:

[{'field': 'custom_fields_41691425', 'value': 'tag_44'},
 {'field': 'comment_value_html',
  'value': '<p>Example comment</p>'}]

这是我用 excel 打开它时得到的。

这里

我想在 excel 中得到这个结构:

HEADER     custom_fields_41691425  | comment_value_html
2nd row:   tag_44                  | <p>Example comment</p>

有什么办法可以做到这一点? 任何帮助将不胜感激。

此致。

模块csv可以保存字典,但它必须是

[
  {'custom_fields_41691425': 'tag_44', 'comment_value_html': '<p>Example comment</p>'},
  {'custom_fields_41691425': 'tag_44', 'comment_value_html': '<p>Example comment</p>'}
]

所以你必须转换它

data = [

    [{'field': 'custom_fields_41691425', 'value': 'tag_44'},
     {'field': 'comment_value_html', 'value': '<p>Example comment</p>'}],

    [{'field': 'custom_fields_41691425', 'value': 'tag_44'},
     {'field': 'comment_value_html', 'value': '<p>Example comment</p>'}],

]

new_data = []

for row in data:
    new_row = {}
    for item in row:
        new_row[item['field']] = item['value']
    new_data.append(new_row)

print(new_data)

之后,您可以轻松保存它

import csv

header = new_data[0].keys()
#print(header)

with open('output.csv', 'w') as fh:
    csv_writer = csv.DictWriter(fh, header)

    csv_writer.writeheader()
    csv_writer.writerows(new_data)

最小的工作示例

import csv

data = [

    [{'field': 'custom_fields_41691425', 'value': 'tag_44'},
     {'field': 'comment_value_html', 'value': '<p>Example comment</p>'}],

    [{'field': 'custom_fields_41691425', 'value': 'tag_44'},
     {'field': 'comment_value_html', 'value': '<p>Example comment</p>'}],

]

new_data = []

for row in data:
    new_row = {}
    for item in row:
        new_row[item['field']] = item['value']
    new_data.append(new_row)

print(new_data)

header = new_data[0].keys()
print(header)

with open('output.csv', 'w') as fh:
    csv_writer = csv.DictWriter(fh, header)

    csv_writer.writeheader()
    csv_writer.writerows(new_data)
import pandas as pd
data = [{'field': 'custom_fields_41691425', 'value': 'tag_44'},

        {'field': 'comment_value_html', 'value': '<p>Example comment</p>'}]
x = []
for d in data:
    x.append(list(d.values()))

df = pd.DataFrame(x)
df.columns = ['field','value']
df.to_csv('data.csv',index=False)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM