Python | Converting a list string to a dictionary



Method # 1: Using dictionary comprehension + split()
Dictionary comprehension can be used to build a dictionary, and the split function can be used to make the necessary splits in list to get a valid key-value pair for the dictionary.

# Python3 demo code
# Converting a list string to a dictionary
# Using a dictionary comprehsion + split ()

  
# initialization string

test_string = ` [Nikhil: 1, Akshat: 2, Akash: 3] `

  
# print original line

< code class = "keyword"> print ( "The original string:" + str (test_string))

  
# using the comprehsion + split () dictionary
# Converting the list string to a dictionary

res = {sub.split ( ":" ) [ 0 ]: sub.split ( ":" ) [ 1 ] for sub in test_string [ 1 : - 1 ]. split ( "," )}

 
# print result

print ( "The dictionary after extraction is:" + str (res))

Output:

 The original string: [Nikhil: 1, Akshat: 2, Akash: 3 ] The dictionary after extraction is: {`Nikhil`:` 1`, `Akash`:` 3`, `Akshat`:` 2`} 

Method # 2: Using eval () + replace ()
This particular task can also be accomplished using a combination of the above two functions, the eval and replace functions. In this method, the eval function performs the functions of a dictionary, the dictionary construction and the replace function perform the necessary replacements. This function is used when keys and values ​​must be converted to an integer.

# Python3 demo code
# Converting the list string to a dictionary
# Using eval () + replace ()

 
# initialization string

test_string = `[120: 1, 190: 2, 140: 3]`

  
# print original line

print ( "The original string:" + str (test_string))

  
# using eval () + replace ()
# Convert list lines to dictionary

res = eval (test_string.replace ( "[" , "{" ). replace ( "]" , "} " ))

  
# print result

print ( "The dictionary after extraction is:" + str (res))

Exit:

 The original string: [120: 1, 190: 2, 140: 3] The dictionary after extraction is: {120: 1, 140: 3, 190: 2}