def wordreplace(s, d):
"""Replaces words in string by dict d. # Thank you @Patrick Artner
for improving dict call to d.get(w, w)!"""
return ' '.join([ d.get(w, w) for w in s.split()])
# this was my old version:
# def wordreplace(s, d):
# """Replaces words in string by dict d."""
# return ' '.join([ d[w] if w in d else w for w in s.split()])
d = {'blvd': 'Boulevard', 'st': "Street", 'sw': 'SW', 's': "S", 'rd': '
Road'}
s1 = "2341 blvd"
s2 = "648 s Kingston rd"
s3 = "sw Beverly st"
wordreplace(s1, d)
# '2341 Boulevard'
wordreplace(s2, d)
# '648 S Kingston Road'
wordreplace(s3, d)
# 'SW Beverly Street'
s.split()
splits by default by a single space thus returns list of words of the string s. Each of the word is loaded into variable w. The for w in s.split()
part of the list expression.
The part before the for
determines what is collected in the resulting list.
if w in d
means: Test whether the word is in the given replacer-dictionary d
. It looks into d.keys()
the keys of the dictionary. When found, it returns the dictionary value d[w]
. else
it returns the word itself w
.
The resulting list ist join
ed using the ' '
as joining element, thus the list of words is re-transformed into a string.
List expressions are very handy and lead often to such one-line functions. So heavily recommend you to learn them.
Instead of typing all key - values into the dictionary form, you can also do:
keys = [ # list here all keys ]
vals = [ # list here all corresponding values in the right order ]
d = {k: vals[i] for i, k in enumerate(keys)}
So again, you can use the power of list expressions to generate with them a dictionary.
# abstract it to a function
def lists2dict(keys_list, vals_list):
return {k, vals_list[i] for i, k in enumerate(key_list)}
# and then call:
d = lists2dict(keys, vals)