
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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'}
- Related Articles
- Add a key value pair to dictionary in Python
- Add key-value pair in C# Dictionary
- Convert string dictionary to dictionary in Python
- Convert tuple to adjacent pair dictionary in Python
- Swift Program to Find Minimum Key-Value Pair in the Dictionary
- Swift Program to Find Maximum Key-Value Pair in the Dictionary
- JavaScript - Convert an array to key value pair
- Convert Nested Tuple to Custom Key Dictionary in Python
- Convert key-values list to flat dictionary in Python
- Accessing Key-value in a Python Dictionary
- Get key from value in Dictionary in Python
- Appending a key value pair to an array of dictionary based on a condition in JavaScript?
- How to convert the string representation of a dictionary to a dictionary in python?
- How to convert a String representation of a Dictionary to a dictionary in Python?
- Python Program to print key value pairs in a dictionary
