Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Python dictionary from string

I have a string with valid python dictionary inside

data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."

I need to extract that dict. I tried with regex but for some reason re.search(r"\{(.*?)\}", data) did not work. Is there any better way extract this dict?

like image 320
Goran Avatar asked Oct 01 '16 14:10

Goran


People also ask

Can you convert a string to a dictionary in Python?

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.

Can we convert string into dictionary?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.


1 Answers

From @AChampion's suggestion.

>>> import re
>>> import ast
>>> x = ast.literal_eval(re.search('({.+})', data).group(0))
>>> x
{'Bar': 'value', 'Foo': '1002803'}

so the pattern you're looking for is re.search('({.+})', data)

You were supposed to extract the curly braces with the string, so ast.literal_eval can convert the string to a python dictionary . you also don't need the r prefix as { or } in a capturing group, () would be matched literally.

like image 151
danidee Avatar answered Oct 30 '22 23:10

danidee