Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to dict? [duplicate]

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).

like image 647
tkbx Avatar asked Sep 06 '25 14:09

tkbx


2 Answers

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.

like image 106
Óscar López Avatar answered Sep 09 '25 10:09

Óscar López


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'>
like image 31
phihag Avatar answered Sep 09 '25 10:09

phihag