python - Return dictionary key if one of key's values is within string -


so have dictionary various keys, , these keys have values in lists of various sizes:

dict = {'a' : ['one', 'two'],         'b' : ['three', 'four', 'five'],         'c' : ['six']} 

if have string follows:

stringa = 'blahfourblah' 

i want return 'b', since 1 of values of key 'b' (i.e. 'four') found within stringa.

i have tried following code:

[k k, v in dict.items() if stringa in v] 

but returns following:

[] 

any appreciated!

the condition stringa in v not correct, since check if entire stringa element in list. element 'blahfourblah' not in list ['three', 'four', 'five']. cannot work.

you can use construct any(..):

[k k, vs in d.items() if any(v in stringa v in vs)]

here every key-value pair check condition any(v in stringa v in vs). means iterate on every element in v, , check if element v substring of stringa. if there such element, any(..) return true. otherwise return false. moment has found such element, stop searching one.

generating:

>>> [k k, vs in d.items() if any(v in stringa v in vs)] ['b'] 

note: not use dict variable name: overwrite dict class reference. used d here.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -