搜索值列表的Python字典

cbb*_*ail 4 python dictionary python-2.7

如果我有一个字典,默认情况下将值设置为列表,我怎么能在字典中搜索某个术语中的所有这些列表呢?

例如:

textbooks = {"math":("red", "large"), "history":("brown", "old", "small")} 
Run Code Online (Sandbox Code Playgroud)

如果有更多的术语和案例可能会再次发生相同的事情,我怎么能说找到所有的键,其值是一个包含"红色"的列表?在我上面的例子中,我唯一想要它找到的就是"数学".

vol*_*ano 10

[k for k, v in textbooks.iteritems() if 'red' in v]
Run Code Online (Sandbox Code Playgroud)

这是Pythonic的简写

res = []
for key, val in textbooks.iteritems():
    if 'red' in val:
        res.append(key)
Run Code Online (Sandbox Code Playgroud)

请参阅Python文档中的列表理解

  • http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions (2认同)