Python search by value

前端 未结 3 551
一个人的身影
一个人的身影 2021-01-06 05:44

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:



        
3条回答
  •  清歌不尽
    2021-01-06 06:03

    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'
    

提交回复
热议问题