Dac121
Dac121

Reputation: 41

Output Python Dictionary 'Values' as binary format

I have trying to solve this issue for a while. Have looked for simple answer but to no avail. Any help much appreciated. I have created a python dictionary and am trying to format the output of the values only as binary data. In other words for each string value in the dictionary I want to output its binary value. My code and the error I am getting are below.

pigpen = {}
pigpen['a'] = 'ETL'
pigpen['b'] = 'ETM'
pigpen['c'] = 'ETR'
pigpen['d'] = 'EML'
pigpen['e'] = 'EMM'
pigpen['f'] = 'EMR'
pigpen['g'] = 'EBL'
pigpen['h'] = 'EBM'
pigpen['i'] = 'EBR'
pigpen['j'] = 'DTL'
pigpen['k'] = 'DTM'
pigpen['l'] = 'DTR'
pigpen['m'] = 'DML'
pigpen['n'] = 'DMM'
pigpen['o'] = 'DMR'
pigpen['p'] = 'DBL'
pigpen['q'] = 'DBM'
pigpen['r'] = 'DBR'
pigpen['s'] = 'EXT'
pigpen['t'] = 'EXL'
pigpen['u'] = 'EXR'
pigpen['v'] = 'EXB'
pigpen['w'] = 'DXT'
pigpen['x'] = 'DXL'
pigpen['y'] = 'DXR'
pigpen['z'] = 'DXB'

import binascii
str = pigpen.values()
print ' '.join(format(ord(string), 'b') for string in str)

Traceback (most recent call last):
  File "pigpen_build.py", line 62, in <module>
    print ' '.join(format(ord(string), 'b') for string in str)
  File "pigpen_build.py", line 62, in <genexpr>
    print ' '.join(format(ord(string), 'b') for string in str)
TypeError: ord() expected a character, but string of length 3 found
>>> 

Upvotes: 2

Views: 1124

Answers (2)

jkr
jkr

Reputation: 19310

@Preston beat me to it with a better answer, but here is a solution that does not use nested list comprehension.

binary_translation = []
for string in a:
    for char in string:
        binary_translation.append(''.join(format(ord(char), 'b')))

Upvotes: 1

Preston Hager
Preston Hager

Reputation: 1631

You are asking ord to find a value based on 3 characters in a string. More on the ord function here. In your for loop you are interacting over a list so your code expanded is like this.

for s in ['ABC','CDE','FGH']:
  print s+', ',

Which would output, ABC, CDE, FGH. To fix this either put another for loop on the actual string, or combine your original list into one string.

1) Another for loop.

print ' '.join(format(ord(string), 'b') for string in (''.join(s for s in str)))

2) Actual string.

str = ''.join(s for s in str)
print ' '.join(format(ord(stirng), 'b') for string in str)

Upvotes: 0

Related Questions