In: Computer Science
Using python. 1. How to create a dictionary that has an integer as a key and a byte as a value? the dictionary keys must contain integers from 0 to 255. It should be similar to UTF-8. When we enter an integer, it should return 1 byte. 2. Create a function when a user gives 1 byte, it should return the key from the previous dictionary.
SOLUTION:-
To make a dictionary of integer keys with byte values you have to simply typecast the integer value to byte for saving the values in the dictionary, for typecast the bytes() function is used which takes integer values as an argument in the required case as done in the code below.
# The code for the required problem is given below with screenshots of code
# for indentation and if you feel any problem then feel free to ask
# 1.
# creating an empty dictionary
intByteDict ={}
# assigning the byte values to the corresponding integer keys
for i in range(0,256):
intByteDict[i] = bytes(i)
# asking the user to input one integer value
# and printing the corresponding byte value
y= int(input("Enter: "))
print(intByteDict[y])
# 2.
# defining a function which takes a byte as arguement
# and return the corresponding integer key
def getReqKey(reqValue):
for keys,values in intByteDict.items():
if values == reqValue:
return keys
return "Key corresponding to this value not exist"
# taking the input of byte from user
x= bytes(input("Enter the byte: "))
#printing the corresponding integer key to byte entered
print(getReqKey(x))