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

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically