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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With