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

2024-04-27 14:59:18 发布

您现在位置:Python中文网/ 问答频道 /正文

在字典中,例如:

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

我怎样才能用“作者”作为键来检索所有有理解力的小说呢。你知道吗


Tags: ofthe字典dictauthorjdendcatcher
3条回答

你可以使用列表理解

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

获取所有小说:

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

我想这是意料之中的结果,但我不确定是否有一个简单的方法来使用理解。你知道吗

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

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

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

相关问题 更多 >