搜索Python字典,其中值是列表 [英] Search Python dictionary where value is list

查看:179
本文介绍了搜索Python字典,其中值是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字典,默认情况下该值设置为列表,那么我可以如何在字典中搜索所有这些列表?

If I had a dictionary where the value was set to a list by default, how could I go about searching all of these lists in the dictionary for a certain term?

例如:

textbooks = {"math":("red", "large"), "history":("brown", "old", "small")} 

同样的事情可能再次发生,我怎么会说找到所有的键值,其中的值是包含红色的列表?在我上面的例子中,我想要找到的只是数学。

With more terms and cases where the same thing might occur again, how could I say find all of the keys in which their value is a list containing "red"? In my example above, the only one I'd want it to find would be "math".

推荐答案

[k for k, v in textbooks.iteritems() if 'red' in v]

res = []
for key, val in textbooks.iteritems():
    if 'red' in val:
        res.append(key)

请参阅清单 Python文档中的理解

这篇关于搜索Python字典,其中值是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆