【问题标题】:Creating a dict of dicts创建字典的字典
【发布时间】:2018-05-22 09:05:48
【问题描述】:

我有几本字典,其中包含书籍的详细信息,其中每个条目对应于不同的书籍。

books = [1,2]
titles = {1 : 'sum_title', 2: 'other_title'}
authors = {1 : 'sum_author', 2 : 'other_author'}
length = {1 : 100, 2 : 200}
chapters = { 1 : 10, 2: 20}

我想遍历所有书籍并将字典组合成单个字典以转换为 .json。这是我所拥有的:

for book in (books):
    All_data.append({"authors": authors[book], "title": titles[book], "length": length[book]})

但是这会返回一个 KeyError。

我首先将数据放入多个字典的原因是我可以分别打印和操作它们。例如;打印所有作者,但不打印标题。他们是我可以将字典组合到另一个字典中并打印键的键值的一种方式,例如打印第 1 本书的作者吗?

非常感谢您的帮助。愿你的代码漂亮且无错误。

【问题讨论】:

  • 发布的代码应该可以工作,你确定它在你的地方坏了吗?您得到的确切错误是什么(带有堆栈跟踪)?
  • All_data 的类型是什么?字典没有 append() 方法。

标签: python dictionary


【解决方案1】:

您可以使用列表推导式来创建新的数据结构:

data = [{'author': authors[b], 'title': titles[b], 'length': length[b]} for b in books]

>>> [{'author': 'sum_author', 'title': 'sum_title', 'length': 100}, {'author': 'other_author', 'title': 'other_title', 'length': 200}]

或者对“字典的字典”的字典理解:

data = {b: {'author': authors[b], 'title': titles[b], 'length': length[b]} for b in books}

>>> {1: {'author': 'sum_author', 'title': 'sum_title', 'length': 100}, 2: {'author': 'other_author', 'title': 'other_title', 'length': 200}}

【讨论】:

  • 使用这种方法,他们是打印特定密钥的一种方式吗?比如打印数据[book[author]]?
  • @LinuxLover 是的,但语法实际上是data[1]['author']。因为data[1] 返回包含第一作者信息的字典,并且该字典中的键'author' 对应于'sum_author'
【解决方案2】:

您可能会发现一种更适用的函数式方法。这不一定比在字典理解中显式编写键更有效,但它更容易扩展:

from operator import itemgetter

keys = ['titles', 'authors', 'length', 'chapters']
values = [titles, authors, length, chapters]

res = [{i: itemgetter(book)(j) for i, j in zip(keys, values)} for book in books]

[{'authors': 'sum_author',
  'chapters': 10,
  'length': 100,
  'titles': 'sum_title'},
 {'authors': 'other_author',
  'chapters': 20,
  'length': 200,
  'titles': 'other_title'}]

【讨论】:

    猜你喜欢
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    相关资源
    最近更新 更多