Tuesday, October 27, 2015

How to convert a string to a dictionary

string_to_dictionary
In [1]:
import ast
In [2]:
#this is a string representation of a dictionary.
string = '{"a":"apple","b":"banana","c":"chips"}'
In [3]:
#note that the key returns an error because it is not a dictionary
string['a']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-e9bc6d56e007> in <module>()
      1 #note that the key returns an error because it is not a dictionary
----> 2 string['a']

TypeError: string indices must be integers, not str
In [4]:
#This evaluates the string representation into a dictionary
d = ast.literal_eval(string)
In [5]:
d
Out[5]:
{'a': 'apple', 'b': 'banana', 'c': 'chips'}
In [6]:
#The key now returns the value
d['a']
Out[6]:
'apple'