How to Convert Bytes to Dictionaries in Python
Working with data often involves handling byte sequences and converting them to more structured formats like dictionaries.
This guide explores various methods to convert bytes objects to dictionaries in Python, covering techniques using ast.literal_eval(), json.loads(), and the steps involved when dealing with single quotes in bytes strings.
Converting Bytes to Dictionaries with ast.literal_eval()
The ast.literal_eval() method safely evaluates a string containing a Python literal, making it a good choice for converting bytes objects representing Python dictionaries.
from ast import literal_eval
my_bytes = b"{'first': 'tom', 'last': 'nolan'}"
my_dict = literal_eval(my_bytes.decode('utf-8'))
print(my_dict) # Output: {'first': 'tom', 'last': 'nolan'}
print(type(my_dict)) # Output: <class 'dict'>
- The
my_bytes.decode('utf-8')converts the bytes object to a string using UTF-8 decoding. - The
literal_eval()method evaluates that string as a Python dictionary, ensuring that the input string consists of only basic Python literal values.
Converting Bytes to Dictionaries with json.loads()
If your bytes object contains a valid JSON string (with double quotes), you can use json.loads():
import json
my_bytes = b'{"first": "tom", "last": "nolan"}'
my_dict = json.loads(my_bytes.decode('utf-8'))
print(my_dict) # Output: {'first': 'tom', 'last': 'nolan'}
print(type(my_dict)) # Output: <class 'dict'>
- The
json.loads()function parses the decoded string into a Python dictionary.