Python Strings to Dictionary

When a string is given with key and value pairs separated by some delimiter (or separator) like a comma (,) we can convert the string into a dictionary and use it as dictionary.

str = "Sujay=23, Rajesh=20, Lahari=19,Nithin=22"

To convert such a string into a dictionary, we have to follow 3 steps.

First, we should split the string into pieces where a comma is found using split() method and then brake the string at equals (=) symbol. This can be done using a for loop as:

Each piece of the string is available in 'y'. The second step is to store these pieces into a list 'lst' using append() method as:

The third step is to convert the list into a dictionary 'd' using dict() function as:

A Python program to convert a string into key-value pairs and store them into a dictionary.