Как преобразовать строку в словарь в Python
Программистам постоянно приходится преобразовывать различные типы данных, и очень важно делать это правильно. В этой статье мы разберем, как можно преобразовать строку в словарь.
Давайте вкратце припомним, что собой представляют строки и словари. Строка — это коллекция символов, каждый из которых, в принципе, тоже считается строкой, поскольку в Python нет соответствующего символьного типа данных. Словарь в Python хранит данные в виде пар ключ-значение. Ключи в словаре должны быть уникальны.
От редакции Pythonist: подробнее о строках читайте в статье «Строки в Python».
А теперь перейдем непосредственно к преобразованию строк в словари.
Конвертируем строку в словарь
Использование метода json.loads ()
Мы можем преобразовать строку в словарь с помощью функции json.loads() . Чтобы ее использовать, нужно импортировать модуль json .
Сперва мы инициализируем строку, которую затем будем преобразовывать в словарь. Для инициализации используется переменная string . В этой строке содержатся названия разных видов птиц. При помощи оператора print выводим нашу строку.
Далее мы преобразуем строку в словарь при помощи функции json.loads() . В качестве параметра этой функции передается переменная string . Результат работы функции (словарь) мы присваиваем переменной res_dict . Затем при помощи оператора print выводим наш словарь.
Использование метода ast.literal.eval()
Еще одна функция, которую применяют для преобразования строк в словари, — ast.literal.eval() . Чтобы ее использовать, нужно импортировать библиотеку ast .
Сначала мы импортируем библиотеку ast . Затем инициализируем строку string , содержащую названия игр. При помощи оператора print выводим нашу строку.
После этого мы конвертируем строку в словарь при помощи функции ast.literal_eval() . В качестве параметра мы передаем ей нашу строку. Результат присваиваем переменной res_dict . После этого снова вызываем оператор print для вывода словаря.
Использование генераторного выражения
Для преобразования строки в словарь можно использовать и генераторное выражение.
Здесь мы инициализируем строку string , в которой будущие пары ключей и значений разделены дефисами и идут через запятую. Наша строка содержит имена студентов и их оценки.
Во вложенном цикле for мы используем строковые функции strip() и split() , чтобы привести пары ключ-значение к нормальному для словаря виду.
Функция split() делит строку на отдельные подстроки, используя в качестве разделителей запятые и дефисы. Функция strip() удаляет пробелы между подстроками. Эта техника не очень эффективна при преобразовании строк, поскольку для получения результата требуется много времени.
В заключение мы распечатали созданный словарь и убедились, что получили именно словарь, выведя его тип.
От редакции Pythonist: о методе split() читайте в статье «Строковые методы split() и join() в Python».
Python program to create a dictionary from a string
Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary. So, let us discuss how we can tackle this problem. Method # 1: Using eval() If we get a string input which completely resembles a dictionary object(if the string looks like dictionary as in python) then we can easily convert it to dictionary using eval() in Python.
Python3
Method # 2: Using generator expressions in python If we get a string input does not completely resemble a dictionary object then we can use generator expressions to convert it to a dictionary.
Python3
The code given above does not convert integers to an int type, if integers keys are there then just line 8 would work
Python3
One additional approach that could be used to create a dictionary from a string is to use the json module. The json module allows you to parse a JSON string and convert it into a dictionary.
Here’s an example of how you could use the json module to create a dictionary from a string:
Python3
The json module is a part of the Python standard library, so you don’t need to install any additional modules to use it.
3 Ways to Convert String to Dictionary in Python

Converting one data type into another is a frequent problem in python programming and it is essential to deal with it properly. Dictionary is one of the data types in python which stores the data as a key-value pair. However, the exchange of data between the server and client is done by python json which is in string format by default.
As it is necessary to convert the python string to dictionary while programming, we have presented a detailed guide with different approaches to making this conversation effective and efficient. But before jumping on the methods, let us quickly recall python string and dictionary in detail.
What is Strings in Python?
Python string is an immutable collection of data elements. It is a sequence of Unicode characters wrapped inside the single and double-quotes. Python does not have a character data type and therefore the single character is simply considered as a string of length 1. To know more about the string data type, please refer to our article «4 Ways to Convert List to String in Python».
Check out the below example for a better understanding of strings in python
For Example
Output
What is Dictionary in Python?
A dictionary is an unordered collection of data elements that is mutable in nature. Python dictionary stores the data in the form of key-value pair.
Hence we can say that dictionaries are enclosed within the curly brackets including the key-value pairs separated by commas. The key and value are separated by the colon between them.
The most important feature of the python dictionaries is that they don’t allow polymorphism. Also, the keys in the dictionary are case-sensitive. Therefore, the uppercase and lowercase keys are considered different from each other. Later, you can access the dictionary data by referring to its corresponding key name.
Check out the below example for a better understanding of dictionaries in python.
For Example
Output
Convert String to Dict in Python
Below are 3 methods to convert string to the dictionary in python:
1) Using json.loads()
You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.
The below example shows the brief working of json.loads() method:
For Example
Output
2) Using ast.literal.eval()
The ast.literal.eval() is an inbuilt python library function used to convert string to dictionary efficiently. For this approach, you have to import the ast package from the python library and then use it with the literal_eval() method.
Check out the below example to understand the working of ast.literal.eval() method.
For Example
Output
3) Using generator expression
In this method, we will first declare the string values paired with the hyphen or separated by a comma. Later we will use the strip() and split() method of string manipulation in the for loop to get the dictionary in the usual format. Strip() method will help us to remove the whitespace from the strings. This method is not as efficient for the conversion of string to dictionary as it requires a lot of time to get the output.
Check out the below example for the string to dictionary conversion using a generator expression
For Example
Output
Conclusion
String and dictionary data type has its own importance when it comes to programming in python. But when we wish to share the data over the network as a client-server connection, it is very important to convert a string into the dictionary for error-free data transfer. We have mentioned the three common methods to explicitly convert the string into a dictionary which will help you to make your programming faster and efficient. To learn more about dictionary and JSON in python, check our detailed guide on “5 Ways to Convert Dictionary to JSON in Python”.
String to Dictionary Python
In this tutorial, we will cover different ways to convert string to dictionary in Python.
Dictionary is one of the most commonly used data types in Python. It is an unordered collection of items of a key/value pair.
Most often, these dictionaries are stored as a string. For example, a dictionary can be stored as a string in JSON format.
To use them in Python, we first need to convert them into a dictionary. Luckily, Python provides us with multiple ways to do so.
Let's see how we can convert a string to a dictionary in Python.

1. String to Dictionary using json module
Python provides a built-in module called json to work with JSON data. This module has multiple methods to deal with JSON data.
One of the methods is loads() which is used to convert a string to a dictionary.
Start with importing the json module. Then, use the loads() method to convert the string to a dictionary.
2. String to Dictionary using ast.literal_eval()
Python has another module called ast that is used to work with Abstract Syntax Trees. This module has a method called literal_eval() that evaluates literal Python expressions and returns the value.
Means it can evaluate a string containing a Python expression and return the value.
Let's use this method to convert a string to a dictionary.
Note : This method is not safe to use. It can evaluate any Python expression. So, it can be dangerous if you are using it with untrusted input.
3. String to Dictionary using eval() function
eval() is a built-in function in Python that can evaluate any Python expression given as a string.
Just like previous method, this method can also be used to convert a string to a dictionary.
Let's see how we can do it.
Both ast.literal_eval() and eval() evaluates any Python expression given as string but ast.literal_eval() is limited evaluating only literal Python expressions.
4. Using Custom Function
Above we have looked at 3 different build-in methods to convert a string to a dictionary. But, if you want to use a custom function, you can do so.
Here is a custom function that can be used to convert a string to a dictionary.
The above function converts a string to a dictionary in the following steps:
- First, it checks if the string is a valid dictionary string. If not, it returns None .
- Then, remove the curly braces from both ends
- Splits the string into key-value pairs using split() method and loop through each pair.
- Now split each pair into key and value
- Finally, it adds the key-value pair to the dictionary.
Conclusion
We have seen 4 different ways to convert a string to a dictionary in Python. All the methods are explained with examples.
Among all the methods, json.loads() is the most popular and recommended method because it safely converts a string to a dictionary.
However, if you want to use a custom function, you can use the function we have created in this tutorial.