Can I change the string to dict?

Asked 2 years ago, Updated 2 years ago, 175 views

s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" -> {'muffin' : 'lolz', 'foo' : 'kitty'}

I want to change the string to dict like this.

My co-developer made me return the string on all functions When replacing a string with a dict type How can I do it without using val()?

python string dictionary

2022-09-22 22:28

1 Answers

In Python 2.6 and later, ast.literal_val(node_or_string) was added to the ast module.

ast.literal_val(node_or_string) is a safer method than val() Take node or string as a factor and return the appropriate string, bytes, numbers, tuples, lists, dicts, sets, booleans, None values.

import ast
ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}") # = {'muffin': 'lolz', 'foo': 'kitty'}


2022-09-22 22:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.