Converting list string to dictionary in Python

PythonServer Side ProgrammingProgramming

Here we have a scenario where if string is presented which has elements in it making it a list. But those elements can also represent a key-value pair making it dictionary. In this article we will see how to take such a list string and make it a dictionary.

With split and slicing

In this approach we use the split function to separate the elements as key value pair and also use slicing to convert the key value pairs into a dictionary format.

Example

 Live Demo

stringA = '[Mon:3, Tue:5, Fri:11]'
# Given string
print("Given string : 
",stringA) # Type check print(type(stringA)) # using split res = {sub.split(":")[0]: sub.split(":")[1] for sub in stringA[1:-1].split(", ")} # Result print("The converted dictionary :
",res) # Type check print(type(res))

Output

Running the above code gives us the following result −

('Given string : 
', '[Mon:3, Tue:5, Fri:11]') ('The converted dictionary :
', {'Fri': '11', 'Mon': '3', 'Tue': '5'})

With eval and replace

The eval function can get us the actual list from a string and then replace will convert each element into a key value pair.

Example

 Live Demo

stringA = '[18:3, 21:5, 34:11]'
# Given string
print("Given string : 
",stringA) # Type check print(type(stringA)) # using eval res = eval(stringA.replace("[", "{").replace("]", "}")) # Result print("The converted dictionary :
",res) # Type check print(type(res))

Output

Running the above code gives us the following result −

('Given string : 
', '[18:3, 21:5, 34:11]') ('The converted dictionary :
', {18: 3, 34: 11, 21: 5})
raja
Updated on 04-Jun-2020 11:18:14

Advertisements