繁体   English   中英

创建一个dicts的词典

[英]Creating a dict of dicts

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

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}

我想遍历所有书籍,并将词典组合成一个单词dict,变成.json。 这是我有的:

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

但是这会返回一个KeyError。

我首先将数据放入多个词典的原因是我可以单独打印和操作它们。 例如; 打印所有作者,但不打印标题。 他们是否可以将字典组合到另一个字典中并打印键的键值,例如打印第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}]

或者对“dicts dict”的词典理解:

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}}

您可能会发现功能性方法更具适应性。 这不一定比在词典理解中明确地编写键更有效,但它更容易扩展:

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'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM