Dictionary Practice Solutions
| categories: Practice
Solutions for the dictionary practice problems.
First to remove the lines with duplicate codes.
# create an empty dictionary to hold the codes we've seen
codes = {}
# create an output file
ofile = file('outlines.txt', 'w')
# read and process each line from the input
for line in file('lines.txt'):
# get the code
code = line[:10] # get the code
if code not in codes: # have we seen it before?
# no, write this line and remember the code
ofile.write(line)
codes[code] = True
# close the output file
ofile.close()
Then to translate text messages.
# initialize our dictionary of acronyms
tla = {
'abt': 'about',
'adn': 'any day now',
'irl': 'in real life',
'lol': 'laugh out loud',
'b4': 'before'
}
def translate(text):
result = []
for word in text.split():
if word in tla:
result.append(tla[word])
else:
result.append(word)
return ' '.join(result)
print translate('I am abt to lol irl')