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
dictvariable name: overwritedictclass reference. useddhere.
Comments
Post a Comment