def multiple_replace(dictionary, text): """Multiple replace Python Cookbook 3.14 page 88 and page 90 """ import re #Create a regular expression from all of the dictionary keys #matching only entire words #regex = re.compile("|".join(map(re.escape, dictionary.keys()))) regex = re.compile(r'\b'+ \ r'\b|\b'.join(map(re.escape, dictionary.keys()))+ \ r'\b' ) #For each match, lookup the corresponding value in the dictionary return regex.sub(lambda match: dictionary[match.group(0)], text) def merge_dictionaries(D1,D2): """merge_dictionaries(D1,D2) Merge two disjoint dictionaries The first argument D1 is modified to hold the result of the merger. If dictionaries are not disjoint an exception is raised """ import types for k in D2.keys(): val = D2[k] if not D1.has_key(k): D1[k] = val else: print 'Dictionaries not disjoint' raise Exception return D1