Find which, if any, dictionary values exist in a string in Python? -
so i'm finding ways find if key/value exists in string, i'm not finding examples allow me access key/value found in string.
basically, have string. let's say:
body = "hi name john" ...and have following dictionary:
names = {"john": "john", "bill": "bill", "jordan": "jordan"} i want see if of names in dictionary contained in string, , if so, want know 1 (assign variable or whatnot).
if assume have these mapped in dictionary reason, i'll show yes it's possible utilize mappings in ways this:
class bodytests(): def __init__(self): self.namemap = {"john": "johnathon", "johnathon": "johnathon", "bill": "william", "wil": "william"} self.greetmap = {"hi": "hello", "aloha": "hello", "hello": "hello", "salutations": "greetings"} def find(self, lookfor, searchin): return set(lookfor.get(x) x in lookfor.viewkeys() & searchin.split()) def findguys(self, abody): return self.find(self.namemap, abody) def findgreets(self, abody): return self.find(self.greetmap, abody) body = "hi name john\nplease call me john\ni wish named bill" foundnames = bodytests().findguys(body) foundgreets = bodytests().findgreets(body) print "python set of names: ", foundnames print "python set of greets: ", foundgreets print "let's dump them out: " s in foundnames: print s s in foundgreets: print s exit() python set of names: set(['william', 'johnathon'])
python set of greets: set(['hello'])
let's dump them out:
william
johnathon
hello
Comments
Post a Comment