- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert byteString key:value pair of dictionary to String in Python
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
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
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'}