从具有不同变量类型的 Python 字典中检索值

Retrieving values from Python dictionary with different variable types

在字典中,例如:

dict = [{'author':'Joyce', 'novel': 'Dubliners'},
{'author':'Greene','novel':'The End of the Affair'},
{'author':'JD Salinger','novel':'Catcher in the Rye'}]

如何使用 'author' 作为 key.

检索所有具有理解力的小说

你可以使用列表理解

[x["novel"] for x in dict if x["author"] == author_name]

获取所有小说:

[x["novel"] for x in dict]

如果您要查找特定作者的所有书籍:

>>> author = 'Joyce'
>>> [d['novel'] for d in data if d['author'] == author]
['Dubliners']

全部小说:

>>> [d['novel'] for d in data]
['Dubliners', 'The End of the Affair', 'Catcher in the Rye']

我想这是预期的结果,但我不确定是否有一种简单的方法可以使用理解来做到这一点。

books = [{'author':'Joyce', 'novel': 'Dubliners'},
    {'author':'Greene','novel':'The End of the Affair'},
    {'author':'JD Salinger','novel':'Catcher in the Rye'}]

nbooks = {}
for book in books:
    author = book['author']
    novel = book['novel']
    nbooks.setdefault(author, []).append(novel)

print(nbooks['Joyce'])