Given a string, with different key-value pairs separated by commas, the task is to convert that string in the dictionary. These types of issues are common in web development where we fetch arguments from requests or get a response as strings. Below are some methods to solve the task.
Method #1: Dictionary comprehension
# Python3 code to demonstrate # converting comma separated string # into dictionary # Initialising string ini_string1 = ’name = akshat, course = btech, branch = computer’ # Printing initial string print ("Initial String", ini_string1) # Converting string into dictionary # using dict comprehension res = dict(item.split("=") for item in ini_string1.split(", ")) # Printing resultant string print ("Resultant dictionary", str(res))
Output #1:
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {‘branch ‘: ‘ computer’, ‘name ‘: ‘ akshat’, ‘course ‘: ‘ btech’}
Method #2: Map and Lambda
# Python3 code to demonstrate # converting comma separated string # into dictionary # Initialising string ini_string1 = ’name = akshat, course = btech, branch = computer’ # Printing initial string print ("Initial String", ini_string1) # Converting string into dictionary # using map and lambda res = dict(map(lambda x: x.split(’=’), ini_string1.split(’, ’))) # Printing resultant string print ("Resultant dictionary", str(res))
Output #2:
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {‘course ‘: ‘ btech’, ‘name ‘: ‘ akshat’, ‘branch ‘: ‘ computer’}
Method #3: eval() function
# Python3 code to demonstrate # converting comma separated string # into dictionary # Initialising string ini_string1 = ’name ="akshat", course ="btech", branch ="computer"’ # Printing initial string print ("Initial String", ini_string1) # Converting string into dictionary # using eval res = eval(’dict(’+ini_string1+’)’) # Printing resultant string print ("Resultant dictionary", str(res))
Output #3:
Initial String name =”akshat”, course =”btech”, branch =”computer”
Resultant dictionary {‘course’: ‘btech’, ‘name’: ‘akshat’, ‘branch’: ‘computer’}
How to convert comma-separated key value pairs into a dictionary using lambda functions?
Question from StackOverFlow
I’m having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions?
fname:John,lname:doe,mname:dunno,city:Florida
Thanks
Answer #1:
If you really want you can even do this with two lambdas, but never try this at work! Just for fun:
s = "name:John,lname:doe,mname:dunno,city:Florida"
d = reduce(lambda d, kv: d.__setitem__(kv[0], kv[1]) or d,
map(lambda s: s.split(’:’), s.split(’,’)),
{})
Answer #2:
There is not really a need for a lambda here.
s = "fname:John,lname:doe,mname:dunno,city:Florida"
sd = dict(u.split(":") for u in s.split(","))
Answer #3:
You don’t need lambda functions to do this:
>>> s = "fname:John,lname:doe,mname:dunno,city:Florida"
>>> dict(item.split(":") for item in s.split(","))
{’lname’: ’doe’, ’mname’: ’dunno’, ’fname’: ’John’, ’city’: ’Florida’}
But you can if you really want to:
>>> dict(map(lambda x: x.split(":"), s.split(",")))
{’lname’: ’doe’, ’mname’: ’dunno’, ’fname’: ’John’, ’city’: ’Florida’}
How to convert values a CSV to a Dictionary in Python
A CSV is an array of data with values separated by commas. A dictionary is a type of data with keys and values.
OPEN THE CSV THEN ITET ON IT AND ADD VALUES TO THE DICTIONARY
Open the file using open (filename). Then, iterate through the resulting object with the for line in the file. Remove the trailing newline with line.strip (" n"), then split the resulting string with line.split (",") to get a key and a value. Add this to the dictionary with dict _1_
MY_SAMPLE.CSV a,1 b,2 d = dict() f = open("my_sample.csv") for line in f: line = line.strip(’ ’) (key, val) = line.split(",") d[key] = val print(d) OUTPUT {’a’: ’1’, ’b’: ’2’}
Archived version
Method # 1: Using Dictionary Comprehension
|
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
|
Exit :
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {’course’: ’btech’, ’name’: ’akshat’, ’branch’: ’computer’}
Method # 3: Using the eval()
Exit :
# 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) )
Initial String name = ”akshat”, course = ”btech”, branch = ”computer”
Resultant dictionary {’course’: ’btech’, ’name’: ’akshat’, ’branch’ : ’computer’}