Python 按值搜索 [英] Python search by value

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

问题描述

我需要一个合适的解决方案来在 Python 的嵌套数据结构中搜索键.让我们假设我有一个值为 'check' 和 dict 的变量,如下所示:

SERVICES = {'域': ['check','whois','register'],'用户':['创建','显示','删除'],'发票': ['toPdf','print']}

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

解决方案

标准方法:

for k, v in SERVICES.items(): # or iteritems in Python 2如果在 v 中检查":打印(k)#'域'休息

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

功能方法:

<预><代码>>>>下一个(过滤器(lambda x:服务[x]中的'检查',服务))'领域'

I need a proper solution to search for a key in a nested data structures in Python. Lets assume that I have variable with value 'check' and dict like this:

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

What is the best way to check in which array-key is the 'check' value and return 'domain'?

解决方案

Standard approach:

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

If you expect to have multiple keys matching the condition, just remove break.

Functional approach:

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

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

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