D
D
Daniil Chernov2019-09-19 12:53:34
Python
Daniil Chernov, 2019-09-19 12:53:34

How to get a dictionary from a string (from str to dict)?

Good afternoon guys.
I have a line:

sunofdog = "{'d': '19', 'mon': '09', 'month': 'Сентябрь',  'address': 'Г. Кемерово ул. Ноградская д. 16, кв. 1'}"

Accordingly, I want to get, for example:
dicktator = превращение_в_словарь(sunofdog)  #  Это например
print dicktator['month']
---
Сентябрь

Reviewed many things.
This option does not work, since the dictionary contains 'address', and it contains commas, respectively, this method tries to cut the value into keys and values:
dicktator = dict(e.split(': ') for e in sunofdog.split(', '))

It also doesn't help:
import json
json.dumps(sunofdog)

I need help guys

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2019-09-19
@dancha

Can be cast to standard json or eval(regular or safe from ast package)

>>> sunofdog = "{'d': '19', 'mon': '09', 'month': 'Сентябрь',  'address': 'Г. Кемерово ул. Ноградская д. 16, кв. 1'}"
>>> a = json.loads(sunofdog.replace("'",'"'))
>>> type(a)
"<class 'dict'>"
>>> b = eval(sunofdog)
>>> type(b)
"<class 'dict'>"
>>> a
{'d': '19', 'mon': '09', 'month': 'Сентябрь', 'address': 'Г. Кемерово ул. Ноградская д. 16, кв. 1'}
>>> a == b
True
>>> 
>>> import ast
>>> c = ast.literal_eval(sunofdog)
>>> a == c
True
>>>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question