Home > Net >  iterate through a string until the exact value is in the dictionary
iterate through a string until the exact value is in the dictionary

Time:05-21

I am trying to decode a binary string using a dictionary with these keys and values

data = "1001011101100100001000100000010011000000000100"

sdict = {"100":"h", "101":"e", "110":"l", "0100":"o","00100":"w","0000100":"r","00000000100":"d"}

This is what I have tried so far:

for i in range(len(data)):
if data[i] in sdict.keys():
    decoded  = sdict[data[i]]
else:
    decoded  = data[i]

It gives me this error

The decoded message should be helloworld

CodePudding user response:

The problem with your code is that you are comparing each character to to strings of multiple characters. That is what the history variable is for in my example below. It collects each character until it reaches a point where the full string matches a key in the dictionary.

You can try this:

decoded = ""   
history = ""  # all characters visited since last key was found
for i in data:
    history  = i                     #  add each character to history
    if history in sdict:             # if history is a key in dictionary
        decoded  = sdict[history]    # add key's value to decoded
        history = ""                 # reset history

output = helloworld

  • Related