Python按值搜索

时间:2014-05-15 13:42:07

标签: python python-2.7

我需要一个适当的解决方案来搜索Python中嵌套数据结构中的键。 让我们假设我有值'check'的变量和这样的dict:

SERVICES = {
    'domain': ['check','whois','register'],
    'user': ['create','show','delete'],
    'invoice': ['toPdf','print']
}

检查哪个数组键是'check'值并返回'domain'的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

标准方法:

for k, v in SERVICES.items(): # or iteritems in Python 2
    if 'check' in v:
        print(k) # 'domain'
        break

如果您希望有多个匹配条件的键,只需删除break

功能方法:

>>> next(filter(lambda x: 'check' in SERVICES[x], SERVICES))
'domain'

答案 1 :(得分:3)

简单地遍历字典键并检查check是否是与键对应的值的值之一。如果您找到它,请将其提交给next来电。

print next(key for key in SERVICES if 'check' in SERVICES[key])
# domain

答案 2 :(得分:2)

SERVICES = {
    'domain': ['check','whois','register'],
    'user': ['create','show','delete'],
    'invoice': ['toPdf','print']
}

print [k for k in SERVICES if 'check' in SERVICES[k]]