将字典的字典转换为电子表格
我的数据是这样的字典的字典(但有更多的字段和名称):
{'Jack': {'age': 15, 'location': 'UK'},
'Jill': {'age': 23, 'location': 'US'}}
我想将其导出到这样的电子表格:
Name Age Location
Jack 15 UK
Jill 23 US
但显然 csv.DictWriter 希望看到这样的字典列表:
[{'name': 'Jack', 'age': 15, 'location': 'UK'},
{'name': 'Jill', 'age': 23, 'location': 'US'}]
什么是最简单的方法将我的字典放入 CSV 文件中?
我认为条目也应该按字母顺序排列,但这在电子表格软件中很容易做到。
My data is a dict of dicts like this (but with a lot more fields and names):
{'Jack': {'age': 15, 'location': 'UK'},
'Jill': {'age': 23, 'location': 'US'}}
I want to export it to a spreadsheet like this:
Name Age Location
Jack 15 UK
Jill 23 US
But apparently csv.DictWriter wants to see a list of dicts like this:
[{'name': 'Jack', 'age': 15, 'location': 'UK'},
{'name': 'Jill', 'age': 23, 'location': 'US'}]
What's the simplest way to get my dict of dicts into a CSV file?
I suppose the entries should be in alphabetical name order, too, but that's easy enough to do in the spreadsheet software.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
datalist
将保存所需的结果。注意:mydict
(向每个数据添加“name”键)。你可能不介意这一点。它比替代方案(复制)更有效。And
datalist
will hold the desired result. Notes:mydict
(adding the 'name' key to each datum). You probably don't mind about that. It's a bit more efficient than the alternative (copying).您可以使用列表理解来获取新的字典列表:
编辑:
d
是您的字典:You can use list-comprehension to get your new list of dicts:
EDIT:
d
is your dict: