Mateusz Wójt
Mateusz Wójt

Reputation: 139

Get key if element matches one of the list items

I have a dictionary that has list of strings as values:

components = {
    'skin': [
        'first',
        'second',
        'third',
    ],
    'hair': [
        'fourth',
        'fifth',
    ]
}

I want to return the key if a matching string was found in one of the lists, i.e.:

fourth -> returns hair

or

second -> returns skin

etc.

Upvotes: 1

Views: 965

Answers (5)

Rafiqul Islam
Rafiqul Islam

Reputation: 225

print([k for k,v in components.items() if 'fourth' in v][0])

Upvotes: 0

Khayrul Islam
Khayrul Islam

Reputation: 1

Try this

components = {
    'skin': [
        'first',
        'second',
        'third',
        ],
    'hair': [
        'fourth',
        'fifth',
    ]
}

def find_key(myDict, value):
    for key in myDict:
        if value in myDict[key]:
            return key
    return -1
    
print(find_key(components, 'fourth'))

Upvotes: -1

timgeb
timgeb

Reputation: 78650

You could write a search algorithm but repeating the search many times is inefficient. If your values in the sublists are unique, you should reverse and flatten your dictionary.

>>> components_rev = {v:k for k, values in components.items() for v in values}
>>> components_rev
{'first': 'skin', 'second': 'skin', 'third': 'skin', 'fourth': 'hair', 'fifth': 'hair'}
>>> components_rev['fourth']
'hair'

Upvotes: 0

Simon Islam
Simon Islam

Reputation: 64

Use the in keyword.

for key in components.keys():
    if search in components[key]:
        print(key)

Beware that, the time complexity of in depends on the container.

  • list - Average: O(n)
  • set/dict - Average: O(1), Worst: O(n)

Upvotes: 1

I'mahdi
I'mahdi

Reputation: 24049

Try this:

>>> def fnd_key(dct, srch_wrd):
...    for k,v in dct.items():
...        if srch_wrd in v:
...            return k

>>> components = {'skin': ['first', 'second', 'third'], 'hair': ['fourth','fifth']}

>>> fnd_key(components, 'second')
'skin'

>>> fnd_key(components, 'fourth')
'hair'

You can try this if value (like:second) exist in multi list:

>>> def fnd_key(dct, srch_wrd):
...    for k,v in dct.items():
...        if srch_wrd in v:
...           yield k

>>> components = {'skin': ['first', 'second', 'third'], 
                  'hair': ['fourth','fifth', 'second']}
>>> for ky in fnd_key(components, 'second'):
...    print(ky)

skin
hair

Upvotes: 1

Related Questions