I have a script that changes a dict to a string and saves it to a file. I'd like to then load that file and use it as a dict, but it's a string. Is there something like int("7")
that can change a string formatted as a dict ({a: 1, b: 2}
) into a dict? I've tried dict()
, but this doesn't seem to be what it does. I've heard of some process involving JSON and eval()
, but I don't really see what this does. The program loads the same data it saves, and if someone edits it and it doesn't work, it's no problem of mine (I don't need any advanced method of confirming the dict data or anything).
Try this, it's the safest way:
import ast
ast.literal_eval("{'x':1, 'y':2}")
=> {'y': 2, 'x': 1}
All the solutions based in eval()
are dangerous, malicious code could be injected inside the string and get executed.
According to the documentation the expression gets evaluated safely. Also, according to the source code, literal_eval
parses the string to a python AST (source tree), and returns only if it is a literal. The code is never executed, only parsed, so there is no reason for it to be a security risk.
This format is not JSON, but YAML, which you can parse with PyYAML:
>>> import yaml
>>> s = '{a: 1, b: 2}'
>>> d = yaml.load(s)
>>> d
{'a': 1, 'b': 2}
>>> type(d)
<type 'dict'>
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