Reputation: 139
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
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
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
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.
Upvotes: 1
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