如何将此词典列表转换为 csv 文件?
我有一个看起来像这样的字典列表:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
我应该怎么做才能将其转换为看起来像这样的 csv 文件:
name,age,weight
bob,25,200
jim,31,180
I have a list of dictionaries that looks something like this:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
What should I do to convert this to a csv file that looks something like this:
name,age,weight
bob,25,200
jim,31,180
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在 python 3 中,情况略有不同,但更简单且不易出错。最好告诉 CSV 您的文件应该使用
utf8
编码打开,因为它使该数据更容易移植到其他人(假设您没有使用限制性更强的编码,例如latin1
)csv
需要newline=''
参数,否则在 excel/opencalc 中打开时,CSV 中会出现空行。或者:我更喜欢使用
pandas
模块中的 csv 处理程序。我发现它对编码问题的容忍度更高,并且 pandas 在加载文件时会自动将 CSV 中的字符串数字转换为正确的类型(int、float 等)。注意:
dataframe.to_dict('records')
csv
模块,您需要为其提供一个OrderedDict
,否则它们将以随机顺序出现(如果在 python <3.5 中工作)。有关更多信息,请参阅:在 Python Pandas DataFrame 中保留列顺序。In python 3 things are a little different, but way simpler and less error prone. It's a good idea to tell the CSV your file should be opened with
utf8
encoding, as it makes that data more portable to others (assuming you aren't using a more restrictive encoding, likelatin1
)csv
in python 3 needs thenewline=''
parameter, otherwise you get blank lines in your CSV when opening in excel/opencalc.Alternatively: I prefer use to the csv handler in the
pandas
module. I find it is more tolerant of encoding issues, and pandas will automatically convert string numbers in CSVs into the correct type (int,float,etc) when loading the file.Note:
utf8
in python3, and figure out headers too.dataframe.to_dict('records')
csv
module, you need to feed it anOrderedDict
or they'll appear in a random order (if working in python < 3.5). See: Preserving column order in Python Pandas DataFrame for more.这是当你有一个字典列表时:
this is when you have one dictionary list:
Pandas 的简短解决方案
a short solution with Pandas
因为@User 和@BiXiC 在此寻求有关UTF-8 的帮助,这是@Matthew 的解决方案的变体。 (我没有权限发表评论,所以我来回答一下。)
Because @User and @BiXiC asked for help with UTF-8 here a variation of the solution by @Matthew. (I'm not allowed to comment, so I'm answering.)
这是另一个更通用的解决方案,假设您没有行列表(可能它们不适合内存)或标题副本(可能
write_csv
函数是通用的):< em>注意:这里使用的 OrderedDict 构造函数仅保留 python >3.4 中的顺序。如果顺序很重要,请使用
OrderedDict([('name', 'bob'),('age',25)])
表单。Here is another, more general solution assuming you don't have a list of rows (maybe they don't fit in memory) or a copy of the headers (maybe the
write_csv
function is generic):Note: the OrderedDict constructor used here only preserves order in python >3.4. If order is important, use the
OrderedDict([('name', 'bob'),('age',25)])
form.这是将数据写入 .csv 文件的最简单方法
This would be the simplest way to write data to .csv file