0

str() turns data into strings but is it possible to undo this with a built in function? exe:

str1 = '{"a": 1, "b": 2}' 

is there a function that can turn this into a dictionary? if not what can I do?

I tried:

dict1 = dict(str1) 

but I only just found out that it's not the way to do it

4
  • See duplicate: use ast.literal_eval(). Commented Feb 5, 2023 at 20:02
  • 2
    Don't use str(), use json.dumps(), which you can reverse with json.loads(). The str() method isn't designed to be reversible (eval will work on it sometimes but not always), whereas JSON encoding is specifically designed to be. (There are other encoding methods, but JSON is a very widely used one and will work great with the type of data you're talking about. It also happens to look a lot like what you get from str() but it's not exactly the same.) Commented Feb 5, 2023 at 20:02
  • The "opposite" is called parsing. The two are not inverses; any data structure can be turned into a string, but not every string represents a valid data structure of a given type. Commented Feb 5, 2023 at 20:12
  • Consider datetime.datetime, which provides the instance method strftime to produce a string and the class method strptime to parse a string. Commented Feb 5, 2023 at 20:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.