Search code examples
python-3.xdictionaryhuffman-code

Compare character in read file with dictionary key and print the corresponding value in Python 3.7.X


Say I have a dictionary like this that has an ASCII value and a corresponding bit string in a list:

{32: ['111'], 101: ['000'], 97: ['1010']...

And I have a file with text, how can I compare each character in the text (converted to ASCII) to the key in the dictionary, and if it matches, then print the bit string?

All of the bit strings would be put together like: 1110001010...

I have this so far but it only prints the first character:

for ch in text:
    for key, value in result.items():
        if ord(ch) == key:
            output = str.join("", value)
        else:
            continue

print(output)

where result is the dictionary above.


Solution

  • You need to preserve the output variable outside the loop, and add to it instead of re-assigning it:

    output = ""
    ...
                output += str.join("", value)
    

    Also, if you know that value is only one item, then you can just do:

    output += value[0]