Python | Converting list string to dictionary

Yet another problem regarding the interconversion between data types is conversion of string of list to a dictionary of keys and values. This particular problem can occur at the places where we need huge amount of string data to be converted to dictionary for preprocessing in Machine Learning domain. Let’s discuss certain ways in which this task can be done.

Method #1 : Using dictionary comprehension + split()
Dictionary comprehension can be used for construction of dictionary and split function can be used to perform the necessary splits in list to get the valid key and value pair for dictionary.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Converting list string to dictionary 
# Using dictionary comprehsion + split()
  
# initializing string
test_string = '[Nikhil:1, Akshat:2, Akash:3]'
  
# printing original string
print("The original string : " + str(test_string))
  
# using dictionary comprehsion + split()
# Converting list string to 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))

chevron_right


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 performed using the combination of above two functions, the eval and replace functions. In this method, eval function performs like dictionary comprehension, constructing the dictionary and replace function performs the necessary replaces. This function is used when keys and values has to be converted to integer.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Converting list string to dictionary 
# Using eval() + replace()
  
# initializing string
test_string = '[120:1, 190:2, 140:3]'
  
# printing original string
print("The original string : " + str(test_string))
  
# using eval() + replace()
# Converting list string to dictionary 
res = eval(test_string.replace("[", "{").replace("]", "}"))
  
# print result
print("The dictionary after extraction is : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.