+2 votes
in Programming Languages by (8.1k points)
I saved a dictionary in a file so that I can use it later. Now when I access the saved dictionary from the file, it is fetched as a string, not as a dictionary. How can I convert the string representation of a dictionary to a dictionary to access its elements.

1 Answer

0 votes
by (15.8k points)

You can use either literal_eval() function of ast module or load() function of yaml module. Have a look at the following example.

>>> import ast
>>> import yaml
>>> aa="{'a':2,'b':3,'c':4,'d':5}"
>>> type(aa)
<type 'str'>

>>> yaml.load(aa)
{'a': 2, 'c': 4, 'b': 3, 'd': 5}
>>> t=yaml.load(aa)
>>> type(t)
<type 'dict'>
>>> t['a']
2

>>> s=ast.literal_eval(aa)
>>> type(s)
<type 'dict'>
>>> s
{'a': 2, 'c': 4, 'b': 3, 'd': 5}
>>> s['c']

...