簡體   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