将字典的字典转换为电子表格

发布于 2024-11-02 21:20:12 字数 475 浏览 0 评论 0原文

我的数据是这样的字典的字典(但有更多的字段和名称):

{'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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月朦胧 2024-11-09 21:20:12
mydict = {'Jack': {'age': 15, 'location': 'UK'}, 
          'Jill': {'age': 23, 'location': 'US'}}

datalist = []

for name in mydict:
  data = mydict[name]
  data['name'] = name
  datalist.append(data)

datalist 将保存所需的结果。注意:

  • 这也会修改 mydict (向每个数据添加“name”键)。你可能不介意这一点。它比替代方案(复制)更有效。
  • 这不是最华丽的单行方式,但它非常具有可读性,恕我直言,这一点更重要
mydict = {'Jack': {'age': 15, 'location': 'UK'}, 
          'Jill': {'age': 23, 'location': 'US'}}

datalist = []

for name in mydict:
  data = mydict[name]
  data['name'] = name
  datalist.append(data)

And datalist will hold the desired result. Notes:

  • This also modifies 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).
  • It's not the most flashy one-line-way-to-do-it, but it's very readable, which IMHO is more important
长途伴 2024-11-09 21:20:12

您可以使用列表理解来获取新的字典列表:

>>> [dict(zip(['name'] + attrs.keys(), [name] + attrs.values())) \  
    for name, attrs in d.iteritems()]
[{'age': 23, 'location': 'US', 'name': 'Jill'},
 {'age': 15, 'location': 'UK', 'name': 'Jack'}]

编辑:d是您的字典:

>>> d
 {'Jack': {'age': 15, 'location': 'UK'}, 'Jill': {'age': 23, 'location': 'US'}}

You can use list-comprehension to get your new list of dicts:

>>> [dict(zip(['name'] + attrs.keys(), [name] + attrs.values())) \  
    for name, attrs in d.iteritems()]
[{'age': 23, 'location': 'US', 'name': 'Jill'},
 {'age': 15, 'location': 'UK', 'name': 'Jack'}]

EDIT: d is your dict:

>>> d
 {'Jack': {'age': 15, 'location': 'UK'}, 'Jill': {'age': 23, 'location': 'US'}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文