How to convert Bytes to Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
3 min

banner

# Table of Contents

  1. Convert Bytes to Dictionary in Python
  2. Convert Bytes to Dictionary using json.loads()
  3. Replacing the single quotes with double quotes before using json.loads()
  4. Converting a Dictionary to Bytes

# Convert Bytes to Dictionary in Python

To convert a bytes object to a dictionary:

  1. Use the bytes.decode() method to convert the bytes to a string.
  2. Use the ast.literal_eval() method to convert the string to a dictionary.
  3. The literal_eval() method safely evaluates a string that contains a Python literal.
main.py
from ast import literal_eval my_bytes = b"{'first': 'bobby', 'last': 'hadz'}" my_dict = literal_eval(my_bytes.decode('utf-8')) print(my_dict) # ๐Ÿ‘‰๏ธ {'first': 'bobby', 'last': 'hadz'} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

convert bytes to dictionary

The code for this article is available on GitHub

We used the bytes.decode() method to convert the bytes object to a string.

main.py
my_bytes = b"{'first': 'bobby', 'last': 'hadz'}" my_str = my_bytes.decode('utf-8') print(my_str) # ๐Ÿ‘‰๏ธ "{'first': 'bobby', 'last': 'hadz'}" print(type(my_str)) # ๐Ÿ‘‰๏ธ <class 'str'>

using bytes decode to convert bytes to string

The bytes.decode() method returns a string decoded from the given bytes. The default encoding is utf-8.

The last step is to pass the string to the ast.literal_eval() method.

The ast.literal_eval() method allows us to safely evaluate a string that contains a Python literal.

main.py
from ast import literal_eval my_bytes = b"{'first': 'bobby', 'last': 'hadz'}" my_dict = literal_eval(my_bytes.decode('utf-8')) print(my_dict) # ๐Ÿ‘‰๏ธ {'first': 'bobby', 'last': 'hadz'} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>
The string may consist of strings, bytes, numbers, tuples, lists, dictionaries, sets, booleans and None.

If the properties in your bytes object are wrapped in double quotes, you can also use the json.loads() method.

# Convert Bytes to Dictionary using json.loads()

This is a two-step process:

  1. Use the bytes.decode() method to convert the bytes to a string.
  2. Use the json.loads() method to parse the string into a dictionary.
main.py
import json my_bytes = b'{"first": "bobby", "last": "hadz"}' my_dict = json.loads(my_bytes.decode('utf-8')) print(my_dict) # ๐Ÿ‘‰๏ธ {'first': 'bobby', 'last': 'hadz'} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

convert bytes to dictionary using json loads

The code for this article is available on GitHub

The json.loads() method parses a JSON string into a native Python object.

main.py
import json json_str = r'{"name": "bobbyhadz", "age": 30}' my_dict = json.loads(json_str) print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

However, the method only accepts valid JSON strings.

If the data being parsed is not a valid JSON string, a JSONDecodeError is raised.

If the properties in your bytes object are not wrapped in double quotes, use the ast.literal_eval() method.

# Replacing the single quotes with double quotes before using json.loads()

An alternative approach would be to replace the single quotes in the string with double quotes.

main.py
import json my_bytes = b"{'first': 'bobby', 'last': 'hadz'}" my_str = my_bytes.decode('utf-8').replace("'", '"') print(my_str) my_dict = json.loads(my_str) print(my_dict) # ๐Ÿ‘‰๏ธ {'first': 'bobby', 'last': 'hadz'} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

replace single quotes with double quotes before using json loads

The code for this article is available on GitHub

We used the str.replace() method to replace all single quotes in the string with double quotes.

However, this could go wrong if some of the values also contain single quotes.

The ast.literal_eval() method safely evaluates the string, so it should be your preferred approach.

# Converting a Dictionary to Bytes

If you need to convert a dictionary to bytes:

  1. Use the json.dumps() method to convert the dictionary to a JSON string.
  2. Use the str.encode() method to convert the string to bytes.
main.py
import json my_dict = { 'first': 'bobby', 'last': 'hadz', 'age': 30, } my_str = json.dumps(my_dict) print(my_str) # ๐Ÿ‘‰๏ธ '{"first": "bobby", "last": "hadz", "age": 30}' my_bytes = my_str.encode('utf-8') print(my_bytes) # ๐Ÿ‘‰๏ธ b'{"first": "bobby", "last": "hadz", "age": 30}'

convert dictionary to bytes

The code for this article is available on GitHub

The json.dumps() method converts a Python object to a JSON formatted string.

Once we have a string, we can use the str.encode() method to convert it to bytes.

The str.encode() method returns an encoded version of the string as a bytes object. The default encoding is utf-8.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev