使用不同的变量类型从Python字典中检索值

时间:2016-01-18 05:29:45

标签: python dictionary list-comprehension

在字典中如下:

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

如何使用'作者'以理解的方式检索所有小说?作为

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

你可以使用列表理解

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

获得所有小说:

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

答案 2 :(得分:0)

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

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