
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Converting list string 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})
- Related Questions & Answers
- Convert string dictionary to dictionary in Python
- Converting all strings in list to integers in Python
- How to convert list to dictionary in Python?
- converting array to list in java
- Dictionary to list of tuple conversion in Python
- Convert dictionary to list of tuples in Python
- List of tuples to dictionary conversion in Python
- How to convert Python Dictionary to a list?
- Converting string to date in MongoDB?
- Converting String to StringBuilder in Java
- Converting string to a binary string - JavaScript
- Python - Clearing list as dictionary value
- Python – Inverse Dictionary Values List
- List vs tuple vs dictionary in Python
- Dictionary creation using list contents in Python
Advertisements