将python字典写入CSV但仅包含特定列
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将python字典写入CSV但仅包含特定列相关的知识,希望对你有一定的参考价值。
我有一个字典,其中有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"]]
答案
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")
另一答案
用熊猫!
import pandas as pd
pd.DataFrame(dictionary).to_csv('filename.csv')
以上是关于将python字典写入CSV但仅包含特定列的主要内容,如果未能解决你的问题,请参考以下文章