Python | Convert comma separated key-value string to dictionary

Method # 1: Using Dictionary Comprehension

# Python3 demo code
# convert string separated by commas
# into dictionary

 
# Initializing string

ini_string1 = `name = akshat, course = btech, branch = computer`

  
# Print start line

print ( "Initial String" , ini_string1)

  
# Convert string to dictionary
  # using dictation

res = dict (item.split ( "=" ) for item in ini_string1.split ( ", " ))

 
# Print the resulting string

print ( "Resultant dictionary" , str (res))

 

Exit :

Initial String name = akshat, course = btech, branch = computer
Resultant dictionar y {`branch`: `computer`, `name`: `akshat`, `course`: `btech`}

Method # 2: Using a map and lambda

# Python3 demo code
# comma-separated string conversion
# to the dictionary

 
# Initializing string

ini_string1 = ` name = akshat, course = btech, branch = computer`

 
# Print initial string

print ( "Initial String " , ini_string1)

  
# Convert string to dictionary
# using map and lambda

res = dict ( map ( lambda x: x.split ( `=` ), ini_string1.split ( `,` )))

 
# Print the resulting string

print ( "Resultant dictionary" , str (res))

 

Exit :

 Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {`course`: `btech`, `name`: `akshat`, `branch`: `computer`}

Method # 3: Using the eval()

# Python3 code for demos
# convert a comma-separated string
# into a dictionary

 
# Initializing string

ini_string1 = `name =" akshat ", course =" btech ", branch =" computer "`

 
# Print start line

print ( " Init ial String " , ini_string1)

  
# Convert string to dictionary
# using eval

res = eval ( ` dict (` + ini_string1 + `)` )

 
# Print the resulting string

print ( "Resultant dictionary" , str (res) )

 

Exit :

Initial String name = ”akshat”, course = ”btech”, branch = ”computer”
Resultant dictionary {`course`: `btech`, `name`: `akshat`, `branch` : `computer`}