Skip to content
Related Articles

Related Articles

Python | Converting list string to dictionary
  • Last Updated : 28 Apr, 2019

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.




# 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))
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.






# 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))
Output :
The original string : [120:1, 190:2, 140:3]
The dictionary after extraction is : {120: 1, 140: 3, 190: 2}

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :