dease
dease

Reputation: 3076

Python search by value

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'?

Upvotes: 4

Views: 173

Answers (3)

vaultah
vaultah

Reputation: 46553

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'

Upvotes: 4

m.wasowski
m.wasowski

Reputation: 6386

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

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

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239573

Simply iterate over the dictionary keys and check if check is one of the values of the value corresponding to the key. If you find it then give it to the next call.

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

Upvotes: 4

Related Questions