Change language

Python program to create a dictionary from a string

| |

# Python3 code to convert
# string to dictionary

 
# Initializing String

string = "{’ A’: 13, ’B’: 14,’ C’: 15} "

 
# eval () convert string to dictionary

Dict = eval (string)

print ( Dict )

print ( Dict [ ’A’ ])

print ( Dict [ ’C’ ])

Output:

 {’C’: 15,’ B’: 14, ’A’: 13} 13 15 

Method # 2: Using generator expressions in Python
If we receive string input that does not completely resemble a dictionary object, then we can use generator expressions to convert it to a dictionary.

# Python3 code to convert
# line to dictionary

 
# Init ializing String

string = "A - 13, B - 14, C - 15 "

  
# Convert string to dictionary

Dict = dict ((x.strip (), y.strip ()) for x, y in (element.split ( ’-’ ) for element in string.split ( ’,’ )))

 

print ( Dict

print ( Dict [ ’A’ ])

print ( Dict [ ’C’ ])

Exit :

 {’C’:’ 15’, ’A’:’ 13’, ’B’:’ 14’} 13 15 

The above code does not convert integers to int type,

if there are integer keys, then only line 8 will work

string = "11 - 13, 12 - 14, 13 - 15"

 

Dict < code class = "keyword"> = dict ((x.strip (), int (y.strip ())) for x , y in (element.split ( ’-’ ) for element in string.split ( ’,’ )))

 

print ( Dict )

Exit:

 {’13’: 15,’ 12’: 14, ’11’: 13} 

Python program to create a dictionary from a string __dict__: Questions

Python program to create a dictionary from a string 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