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

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • See duplicate: use `ast.literal_eval()`. – AKX Feb 05 '23 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.) – Samwise Feb 05 '23 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. – chepner Feb 05 '23 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. – chepner Feb 05 '23 at 20:23

0 Answers0