Python Dictionaries – Convert string to dictionary

In this post we will be creating a Python script that will convert a string representation of a dictionary to a dictionary. To do this we will be using the ast module, in particular the ‘literal_eval()’ which evaluates strings containing Python values without the need to parse them.

See the string representation of our string for this example below.

string="{'Spain' : 'Madrid', 'Italy' : 'Rome', 'France' : 'Paris'}"

To convert the above to a dictionary, see the snippet of code below.

import ast

string="{'Spain' : 'Madrid', 'Italy' : 'Rome', 'France' : 'Paris'}"

Dict =ast.literal_eval(string)

for key, value in Dict.items():
    print(key, value)

The above would return the following as output.

Spain Madrid
Italy Rome
France Paris

Leave a Reply