Python Convert Dict to String or String to Dict – Python Tutorial

By | March 18, 2024

In this tutorial, we will introduce how to convert a python dict to string or string to a dict.

Python dict to string

We can use str() to convert a python dict to string. Here is the example:

x = {}
x["name"]="tom"
x["age"] = 23
print(type(x))
y = str(x)
print(type(y))
print(y)

Run this code, we will see:

<class 'dict'>
<class 'str'>
{'name': 'tom', 'age': 23}

Here we will convert dict x to string y.

Convert a string dict to a dict in python

We can use eval() to implement it.

For example:

y = '{"x":200, "y":2}'
z = eval(y)
print(type(z))
print(z)

Here y is a python dict string, we will convert it to dict z.

Run this code, we will see:

<class 'dict'>
{'x': 200, 'y': 2}