Change language

Python | Convert comma separated key-value string to dictionary

| | | | |

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

# 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’}

Python | Convert comma separated key-value string to dictionary __dict__: Questions

Python | Convert comma separated key-value string to dictionary Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method