I have to replace the north, south, etc with N S in address fields.
If I have
list = {\'NORTH\':\'N\',\'SOUTH\':\'S\',\'EAST\':\'E\',\'WEST\':\'W\'}
One option I don't think anyone has yet suggested is to build a regular expression containing all of the keys and then simply do one replace on the string:
>>> import re
>>> l = {'NORTH':'N','SOUTH':'S','EAST':'E','WEST':'W'}
>>> pattern = '|'.join(sorted(re.escape(k) for k in l))
>>> address = "123 north anywhere street"
>>> re.sub(pattern, lambda m: l.get(m.group(0).upper()), address, flags=re.IGNORECASE)
'123 N anywhere street'
>>>
This has the advantage that the regular expression can ignore the case of the input string without modifying it.
If you want to operate only on complete words then you can do that too with a simple modification of the pattern:
>>> pattern = r'\b({})\b'.format('|'.join(sorted(re.escape(k) for k in l)))
>>> address2 = "123 north anywhere southstreet"
>>> re.sub(pattern, lambda m: l.get(m.group(0).upper()), address2, flags=re.IGNORECASE)
'123 N anywhere southstreet'