Convert byteString key:value pair of dictionary to String in Python

PythonServer Side ProgrammingProgramming

The byte string in python is a string presentd with letter b prefixed on it. In this article we will see how to convert a dictionary with the bytecode string into a normal dictionary which represents only strings.

With decode and ascii

Python string method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding. We use it to convert the bytecode value into normal asci values by supplying ascii as the parameter to the decode function.

Example

 Live Demo

bstring = {b'day': b'Tue', b'time': b'2 pm', b'subject': b'Graphs'}
print(bstring)
# Use decode
stringA = {y.decode('ascii'): bstring.get(y).decode('ascii') for y in bstring.keys()}
# Result
print(stringA)

Output

Running the above code gives us the following result −

{'subject': 'Graphs', 'day': 'Tue', 'time': '2 pm'}
{u'time': u'2 pm', u'day': u'Tue', u'subject': u'Graphs'}

With decode and utf-8

We can take a similar approach as above but use utf-8 this time. Design a for loop for key value pair and iterate through each pair to convert the values into utf-8 representation.

Example

 Live Demo

bstring = {b'day': b'Tue', b'time': b'2 pm', b'subject': b'Graphs'}
print(bstring)
# Use decode
stringA = {}
for key, value in bstring.items():
   stringA[key.decode("utf-8")] = value.decode("utf-8")
# Result
print(stringA)

Output

Running the above code gives us the following result −

{'subject': 'Graphs', 'day': 'Tue', 'time': '2 pm'}
{u'time': u'2 pm', u'day': u'Tue', u'subject': u'Graphs'}
raja
Published on 20-May-2020 14:13:57
Advertisements