SIM777
SIM777

Reputation: 13

How to extract python dictionary from a string

I have the following string which consists of a url followed by a valid python dictionary as shown: data = "https:google.com [{'Foo': u'1002803', 'Bar': 'value'},{'Foo': u'1002803', 'Bar': 'value'}]" I want to just extract the dictionary part from the string.Note that the dictionary can be nested.I just want to somehow eliminate that link part from the string ("https:google.com)

I dont know how to do this.Thought of using ".split()" method but it doesnt work

Upvotes: 0

Views: 227

Answers (1)

rahul.m
rahul.m

Reputation: 5854

By using https://docs.python.org/3/library/ast.html#module-ast

try this

import ast
data = "https:google.com [{'Foo': u'1002803', 'Bar': 'value'},{'Foo': u'1002803', 'Bar': 'value'}]"
dict_data = data.split(" ", 1)
# dict_data = data.split(" ", maxsplit=1) mentioned by **Syntactical Remorse**
print(ast.literal_eval(dict_data[1]))

Upvotes: 2

Related Questions