Python convert string dict to dict

How To Convert String Representation Of Dict To Dict In Python?

Converting string representation of dict to dict in Python is a common step in developing your project. String data is easily conveyed through methods, so data type models are often converted back and forth to facilitate communication with each other. This article will help you complete it.

Two ways to convert string representation of dict to dict in Python

Using json.loads() method

As we introduced above, converting data to string aims to transmit it more gently and quickly. So Python will support methods to converting string representation of dict to dict easily, specifically here is using the loads() method from the json library.

The result returns a Python object.

Specific examples of the requirements of the problem:

import json # Init json string jsonStr = '' # Using json.loads() to convert dictObject = json.loads(jsonStr) # Print json string print("The original string : " + str(jsonStr)) # Print dict object print("The converted dictionary : " + str(dictObject)) # Check data type print(type(jsonStr)) print(type(dictObject))

The original string : The converted dictionary :

First, we import the json library, which contains json related methods and loads() method.

Читайте также:  Next node in javascript

Next, we initialize a json string with the internal format of a dict. we use the json.loads() methods to unformat the json string, and as a result, we get a dict object like the one we showed above.

Methods are so simple as to give perfect results.

Using eval() function

This is a built-in function in Python, and it has the same task as the json.loads() method. However, it is a function developed by Python to be used independently without any other library.

It will return a Python expression from a string, distinguishing it from the json.loads() method is that it can recognize any expression in Python, not necessarily a data type as a json string.

# Init json string jsonStr = '' # Using eval() function to convert dictObject = eval(jsonStr) # Print json string print("The original string : " + str(jsonStr)) # Print dict object print("The converted dictionary : " + str(dictObject)) # Check data type print(type(jsonStr)) print(type(dictObject))

The original string : The converted dictionary :

we replaced json.loads() method with eval() function and it gives the same result

Summary

Regardless of json.loads() method or eval() function gives the same result in converting string representation of dict to dict in Python. It may differ in other cases, which you will learn in upcoming articles. Thank you for reading the article. Good luck to you.

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

Источник

Как из строки получить словарь (из str в dict)?

sim3x

А почему не стоит? Пусть пишут кривой код и учатся на ошибках. А то все в программирование поперлись и всякую ерунду спрашивают, потому что лень почитать ошибки. Вот там json наверняка ругалась на кавычки.

Vaindante

dancha

Хахаха, я и делал через eval, но я забыл что у меня переменная до этого еще одну обработку проходила.
Извините за лишний вопрос и спасибо за ответ)))

Все указанные решения работают в некоторых частных случаях и могут сломаться в любой момент.

В общем случае, нет стандартного способа получить строку в указанном топикстартером виде и синтаксис он не указал, поэтому я предполагаю, что это результат какой-то разрушающей операции типа str от питоновского объекта. Если речь идёт действительно об str, то он вполне способен сгенерировать довольно разные строки, которые будут ломать любой из указанных способов.

Например, вариант с ремлейсом ломается если внутри уже есть кавычки. Вариант с эвалом не стоит советовать, так как на определенных данных он может привести к исполнению стороннего кода. Вариант с literal_eval сломается на сложных объектах (а так как мы не знаем, как автор получил свою строку, можно допустить, что там может быть что угодно)

Tishka17, У меня в конфиге есть возможность задать питонье выражение/функцию которая потом выполняется exec`ом или eval`ом — если клиент захочет вызвать сегментейшен еррор или поломать приложение — то кто-будет виноват? «Дыра» в приложении или сам себе злобный Буратино (клиент)? Проблема не в eval, а в программистах которые его не там используют, если json парсится eval`ом в веб приложении и endpoint может дергать кто угодно — безусловно дыра. Если json парсится eval`ом во внутреннем скрипте препроцессинга миллионов записей для БД, что позволяет увеличить скорость обработки чуть ли не на 40% — это не зло и не дыра, это осознанное, и правильное решение.

javedimka,
Если у вас конфиг обрабатывается эвалом — это уже не конфиг, а скрипт. Соответственно, если ваша программа позволяет выполнять пользователю в ней произвольные скрипты, вы должны многое предусмотреть. Например, программа, работающая от рута скорее всего не должна исполнять скрипты заполненные обычным юзером, так как это будет повышение привилегий. Обычно конфиги программ же делают в любом текстовом формате как раз чтобы не дать простому юзеру своей ошибкой удалить все данные или сломать компьютер (да, евал может не просто вызвать сегфолт, а вызвать произвольную системнуюкоманду вполть до `rm -rf ~/*`)

Если json в базе эвалом парсится быстрее чем с помощью json — это довольно странно и, вероятно, вы делаете что-то не то. Мой простой тест выдал такие результаты на парсинге эталонного набора (меньше — лучше)

json - 1.034 ujson - 0.344 eval - 16.797
import json from timeit import timeit import ujson orig = ": list(range(i, i + 100)) for i in range(100)> data = json.dumps(orig) assert ujson.loads(data) == eval(data) n=1000 print(" json", timeit('json.loads(data)', globals=globals(), number=n)) print("ujson", timeit('ujson.loads(data)', globals=globals(), number=n)) print(" eval", timeit('eval(data)', globals=globals(), number=n))

Я не отрицаю, что eval действительно где-то может оказаться полезен именно для парсинга данных, но это должны быть данные правильным образом подготовленные, полученные из доверенного источника и, конечно, надо быть уверенным что это действительно нужная и не имеющая лучших альтернатив оптимизация

Предусматривать, конечно, нужно, например, скрипт запускать не из под рута

Результаты тестов удивительные, ничего не скажу. Сейчас проверить не могу ошибся ли я в своих высказываниях про скорость, т.к. оригинальный скрипт не был закомичен и впоследствии был переписан на go

seregazolotaryow64

import ast import json nmq = input() nm = nmq.split(" ") n = int(nm[0]) m = int(nm[1]) feedqueres = [] feedform = <> feed = <> for i in range(n): feeddata = str(input()) feedqueres.append(feeddata) feedform.update(>) for i in range(len(feedqueres)): data = json.loads(feedqueres[i]) feedform['offers'].update(ast.literal_eval(data['offers'])) feed.update(>) for i in range(m): readydata = feedform['offers'][i] feed['offers'].update(ast.literal_eval(readydata)) print(json.dumps(feed))
Traceback (most recent call last): File "main.py", line 24, in feedform['offers'].update(ast.literal_eval(data['offers'])) File "/usr/lib/python3.8/ast.py", line 99, in literal_eval return _convert(node_or_string) File "/usr/lib/python3.8/ast.py", line 98, in _convert return _convert_signed_num(node) File "/usr/lib/python3.8/ast.py", line 75, in _convert_signed_num return _convert_num(node) File "/usr/lib/python3.8/ast.py", line 66, in _convert_num _raise_malformed_node(node) File "/usr/lib/python3.8/ast.py", line 63, in _raise_malformed_node raise ValueError(f'malformed node or string: ') ValueError: malformed node or string: [, ]

Источник

3 Ways to Convert String to Dictionary in Python

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

a = "Python Programming is Fun" print(a)
Python Programming is Fun 

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

sample_dict = < "vegetable": "carrot", "fruit": "orange", "chocolate": "kitkat" > print(sample_dict)

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

import json original_string = '' # printing original string print("The original string is : " + str(original_string)) # using json.loads() method result = json.loads(original_string) # print result print("The converted dictionary is : " + str(result))
The original string is : The converted dictionary is :

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

import ast original_String = '' # printing original string print("The original string is : " + str(original_String)) # using ast.literal_eval() method result = ast.literal_eval(original_String) # print result print("The converted dictionary is : " + str(result))
The original string is : The converted dictionary is :

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

original_String = "John - 10 , Rick - 20, Sam - 30" print("The original string is ",original_String) #using strip() and split() methods result = dict((a.strip(), int(b.strip())) for a, b in (element.split('-') for element in original_String.split(', '))) #printing converted dictionary print("The resultant dictionary is: ", result)
The original string is John - 10 , Rick - 20, Sam - 30 The resultant dictionary is:

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”.

Источник

Оцените статью