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"

strings to dictionary steps:

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:

CopiedCopy Code

for x in str.split(','): 
    y= x.split('=')

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:

CopiedCopy Code

lst.append(y)

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

CopiedCopy Code

d = dict(lst)

strings to dictionary example:

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

CopiedCopy Code

str = "Vijay=23,Ganesh=20,Lakshmi=19,Nikhil=22" 
lst=[] 
for x in str.split(','): 
   y= x.split('=') 
   lst.append(y) 
d = dict(lst) 
d1={} 
for k, v in d.items(): 
   d1[k] = int(v) 
print(d1)