user10391380
user10391380

Reputation:

Decoding message using dictionary on string in Python

When I'm using a dictionary to replace values in a string for decoding of a message, how do I put it in such that the function doesn't read a replaced value as a key and replace a replaced value again?

def decipher_message(translation_guide, message):
    t = read_translation_guide_into_dictionary(translation_guide)
    e = read_message(message)

    print(t)

    print(e)

    for key, value in t.items():
            f = e
            e = f.replace(key, value)

    return e

Output:

{'a': 'm', 'b': 'a', 'c': 'c', 'd': 'y', 'e': 't', 'f': 'v', 'g': 'o', 'h': 'u', 'i': 'x', 'j': 'e', 'k': 'j', 'l': 'w', 'm': 'f', 'n': 'z', 'o': 'd', 'p': 'l', 'q': 'i', 'r': 'k', 's': 'h', 't': 'n', 'u': 'g', 'v': 'b', 'w': 'q', 'x': 's', 'y': 'p', 'z': 'r'}

"qa mqtbppd vjqtu mghto! esbtr dgh mgz mqtoqtu aj gs rqto xezbtujz. q ahxe ejpp dgh, qex whqej vgzqtu sbfqtu bpp esj ljbpes qt esj lgzpo. qm dghzj pggrqtu mgz qe, q vhzqjo b aby eg qe bzghto lsjzj dghzj xebtoqtu tgl! zjajavjz esghus: ljbpes qxte jfjzdesqtu qt esj lgzpo!"

'"if finallp being fdgnd! nhank pdg fdr finding fe dh kind snranger. i fgsn nell pdg, ins qgine bdring habing all nhe qealnh in nhe qdrld. if pdgre lddking fdr in, i bgried a fap nd in ardgnd qhere pdgre snanding ndq! refefber nhdggh: qealnh isnn eberpnhing in nhe qdrld!"'

Upvotes: 2

Views: 3011

Answers (2)

blhsing
blhsing

Reputation: 106465

You can use str.join with the following generator expression that iterates over the string to translate each character:

def decipher(translation, message):
    t = read_translation(translation)
    e = read_message(message)
    return ''.join(t.get(c, c) for c in e)

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599510

Rather than iterating through the dictionary and running a replace against the whole string, you should iterate through the string and replace each character with its value in the dict:

decoded = []
for letter in e:
    decoded.append(t.get(letter, letter))
return ''.join(decoded)

Note also that Python has a built-in string translate method, which takes a table which can be generated from your dict:

table = str.maketrans(t)
return e.translate(table)

Upvotes: 5

Related Questions