can you write a str.replace() using dictionary values in Python?

user1947457 picture user1947457 · Jan 4, 2013 · Viewed 90.8k times · Source

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'}
address = "123 north anywhere street"

Can I for iterate over my dictionary values to replace my address field?

for dir in list[]:
   address.upper().replace(key,value)

I know i'm not even close!! But any input would be appreciated if you can use dictionary values like this.

Answer

rich tier picture rich tier · Jan 4, 2013
address = "123 north anywhere street"

for word, initial in {"NORTH":"N", "SOUTH":"S" }.items():
    address = address.replace(word.lower(), initial)
print address

nice and concise and readable too.