将python字典写入CSV但仅包含特定列

问题描述 投票:-3回答:2

我有一个字典,其中有8列我需要写入CSV,它工作得很好,但我只想将我的字典的特定列转换为csv。怎么做

{'data': [{'channel_id': 'UCqTFe5Dz3mpixUrLfMmY6dw', 'title': 'Manoyek', 'channel_img': 'https://yt3.ggpht.com/a-/AN66SAx-JBOt1_NI6nXTBL2R95kDBaR6Spy9i4_q-g=s240-mo-c-c0xffffffff-rj-k-no', 'desc': 'Jestem Adrian' , 'subscriberCount_gained': 587372, 'subscriberCount_lost': 0}]}

from pandas import DataFrame data = DataFrame.from_dict(diction) print(data) data_to_write = data[["channel_id", "channel_img", "desc"]]

python dictionary export-to-csv
2个回答
2
投票
import pandas as pd

dictionary = {'data': [{'channel_id': 'UCqTFe5Dz3mpixUrLfMmY6dw', 'title': 'Manoyek', 'channel_img': 'https://yt3.ggpht.com/a-/AN66SAx-JBOt1_NI6nXTBL2R95kDBaR6Spy9i4_q-g=s240-mo-c-c0xffffffff-rj-k-no', 'desc': 'Jestem Adrian' , 'subscriberCount_gained': 587372, 'subscriberCount_lost': 0}]}

data = pd.DataFrame.from_dict(dictionary["data"])

data_to_write = data[["channel_id", "channel_img", "desc"]]
data_to_write.to_csv("filename.csv")

0
投票

用熊猫!

import pandas as pd

pd.DataFrame(dictionary).to_csv('filename.csv')
© www.soinside.com 2019 - 2024. All rights reserved.