
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Convert string dictionary to dictionary in Python
- Converting all strings in list to integers in Python
- How to convert list to dictionary in Python?
- Dictionary to list of tuple conversion in Python
- Convert dictionary to list of tuples in Python
- List of tuples to dictionary conversion in Python
- Appending a dictionary to a list in Python
- How to convert a string to dictionary in Python?
- Python – Inverse Dictionary Values List
- How to convert Python Dictionary to a list?
- converting array to list in java
- Convert key-values list to flat dictionary in Python
- How to convert the string representation of a dictionary to a dictionary in python?
- How to convert a String representation of a Dictionary to a dictionary in Python?
- Dictionary creation using list contents in Python

Advertisements