+2 votes
in Programming Languages by (75.0k 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

+1 vote
by (353k points)
selected by
Best answer

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']

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