
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert List of Strings to Dictionary in Python
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
stringA = '[Mon:3, Tue:5, Fri:11]' # Given string print("Given string : \n",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 : \n",res) # Type check print(type(res))
Output
Running the above code gives us the following result −
('Given string : \n', '[Mon:3, Tue:5, Fri:11]') ('The converted dictionary : \n', {'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
stringA = '[18:3, 21:5, 34:11]' # Given string print("Given string : \n",stringA) # Type check print(type(stringA)) # using eval res = eval(stringA.replace("[", "{").replace("]", "}")) # Result print("The converted dictionary : \n",res) # Type check print(type(res))
Output
Running the above code gives us the following result −
('Given string : \n', '[18:3, 21:5, 34:11]') ('The converted dictionary : \n', {18: 3, 34: 11, 21: 5})
Advertisements