Python | Convert key-value pair comma separated string into dictionary
Given a string, with different key-value pairs separated with commas, the task is to convert that string into the dictionary. These types of problems are common in web development where we fetch arguments from queries or get a response in the form of strings. Given below are a few methods to solve the task.
Method #1: Using dictionary comprehension
# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name = akshat, course = btech, branch = computer' # Printing initial stringprint ("Initial String", ini_string1) # Converting string into dictionary# using dict comprehensionres = dict(item.split("=") for item in ini_string1.split(", ")) # Printing resultant stringprint ("Resultant dictionary", str(res)) |
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {‘branch ‘: ‘ computer’, ‘name ‘: ‘ akshat’, ‘course ‘: ‘ btech’}
Method #2: Using Map and lambda
# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name = akshat, course = btech, branch = computer' # Printing initial stringprint ("Initial String", ini_string1) # Converting string into dictionary# using map and lambdares = dict(map(lambda x: x.split('='), ini_string1.split(', '))) # Printing resultant stringprint ("Resultant dictionary", str(res)) |
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {‘course ‘: ‘ btech’, ‘name ‘: ‘ akshat’, ‘branch ‘: ‘ computer’}
Method #3: Using eval() function
# Python3 code to demonstrate # converting comma separated string# into dictionary # Initialising stringini_string1 = 'name ="akshat", course ="btech", branch ="computer"' # Printing initial stringprint ("Initial String", ini_string1) # Converting string into dictionary# using evalres = eval('dict('+ini_string1+')') # Printing resultant stringprint ("Resultant dictionary", str(res)) |
Initial String name =”akshat”, course =”btech”, branch =”computer”
Resultant dictionary {‘course’: ‘btech’, ‘name’: ‘akshat’, ‘branch’: ‘computer’}



Please Login to comment...