Convert dictionary to string with double quotes in Python

avatar

Borislav Hadzhiev

Last updated: Sep 8, 2022

banner

Photo from Unsplash

Convert dictionary to string with double quotes in Python #

Use the json.dumps() method to convert a dictionary to a string with double quotes, e.g. json_str = json.dumps(my_dict). The json.dumps() method converts a Python object to a JSON formatted string with the dictionary's keys and string values wrapped in double quotes.

main.py
import json my_dict = {'id': 1, 'name': 'bobbyhadz'} json_str = json.dumps(my_dict) print(json_str) # 👉️ {"id": 1, "name": "bobbyhadz"} print(type(json_str)) # 👉️ <class 'str'>

We used the json.dumps() method to convert a dictionary to a string with double quotes.

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

If you need to pretty print the dictionary as JSON, set the indent argument to 4 in the call to json.dumps().

main.py
import json my_dict = {'id': 1, 'name': 'bobbyhadz'} json_str = json.dumps(my_dict, indent=4) # { # "id": 1, # "name": "bobbyhadz" # } print(json_str)

If indent is set to a non-negative integer, the JSON array elements or object members get pretty-printed with the specified indent level.

The keys in the dictionary and the string values get wrapped in double quotes when converted to a JSON string.

If you need to convert the JSON string back to a native Python dictionary, use the json.loads() method.

main.py
import json my_dict = {'id': 1, 'name': 'bobbyhadz'} json_str = json.dumps(my_dict) print(json_str) # 👉️ {"id": 1, "name": "bobbyhadz"} native_dict = json.loads(json_str) print(native_dict) # 👉️ {'id': 1, 'name': 'bobbyhadz'}

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

The process of converting a native Python object to a JSON string is called serialization.

The process of converting a JSON string to a native Python object is called deserialization.

By default, the JSONEncoder class can convert the following objects and types to JSON.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

Directly passing a value of any other type to the json.dumps() method is not supported.

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.