简体   繁体   中英

Using a loop to make a dictionary

I'm trying to make a binary2acii and vise versa Dictonary via Python shell. I'm a bit stuck:

  1. I make a new Dictonary
  2. I need to declare, that it goes from 0-127
  3. Make a loop to go through all options

I'm new to this.

binary2ascii = {}, 
format (127,"08b")   
for i in range(0,127): chr(i)

It sounds like you need to spend a little more time learning Python essentials.

Anyway, here's a way to make a dictionary that handles both converting a bitstring to a character and vice versa. I just loop over range(65, 70) to keep the output small.

from pprint import pprint

binary2ascii = {}
for i in range(65, 70):
    bits = format(i, "08b")
    char = chr(i)
    binary2ascii[bits] = char
    binary2ascii[char] = bits

pprint(binary2ascii)    

output

{'01000001': 'A',
 '01000010': 'B',
 '01000011': 'C',
 '01000100': 'D',
 '01000101': 'E',
 'A': '01000001',
 'B': '01000010',
 'C': '01000011',
 'D': '01000100',
 'E': '01000101'}

Also, you can accomplish such 'translation' without the dictionary, like this:

def asc2binii(ch):
    return bin(ord(ch))

def bin2ascii(bin_int):
    return chr(int(bin_int, 2))

char_input="a"
binary_repr = asc2binii(char_input)
print(binary_repr)
ch_returned = bin2ascii(binary_repr)
print(ch_returned)

will print:

0b1100001
a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM