Python - Converting list string to dictionary
Last Updated : 15 Jan, 2025
Converting a list string to a dictionary in Python involves mapping elements from the list to key-value pairs. A common approach is pairing consecutive elements, where one element becomes the key and the next becomes the value. This results in a dictionary where each pair is represented as a key-value entry.
Using dictionary comprehension
Dictionary comprehension can be used for the construction of a dictionary and the split function can be used to perform the necessary splits in a list to get the valid key and value pair for a dictionary.
Python a = '[Nikhil:1, Akshat:2, Akash:3]' res = { # Extract key and value, converting value to integer item.split(":")[0]: int(item.split(":")[1]) for item in a[1:-1].split(", ") } print(res)
Output{'Nikhil': 1, 'Akshat': 2, 'Akash': 3}
Explanation:
- String Slicing: a[1:-1] removes the first ([) and last (]) characters from the string, leaving only the substring: "Nikhil:1, Akshat:2, Akash:3".
- Splitting by Comma: .split(", ") creates a list like ["Nikhil:1", "Akshat:2", "Akash:3"].
- Dictionary Comprehension: For each item in that list, item.split(":")[0] becomes the dictionary key, and int(item.split(":")[1]) becomes the value.
Let's explore more methods to convert list string to dictionary.
Using ast.literal_eval
If list string is in a Python-like format ('[("Nikhil", 1), ("Akshat", 2), ("Akash", 3)]'), we can use the built-in ast.literal_eval function to safely parse it into a Python object. Then, if the parsed object is a list of key-value pairs (tuples), we can convert it to a dictionary with dict().
Python import ast a = '[("Nikhil", 1), ("Akshat", 2), ("Akash", 3)]' # evaluate the string to a list of tuples b = ast.literal_eval(a) res = dict(b) print(res)
Output{'Nikhil': 1, 'Akshat': 2, 'Akash': 3}
Explanation:
- ast.literal_eval(a) converts the string into an actual Python list of tuples-
[('Nikhil', 1), ('Akshat', 2), ('Akash', 3)]
. - dict(b) takes that list of (key, value) tuples and constructs a dictionary-
[('Nikhil', 1), ('Akshat', 2), ('Akash', 3)]
.
Using re.findall()
re.findall()
extract key-value pairs from a string and convert them into a dictionary. It efficiently matches patterns for keys and values, then uses dict()
to create the dictionary.
Python import re a = '[Nikhil:1, Akshat:2, Akash:3]' # Use regular expression to extract key-value pairs res = dict(re.findall(r'(\w+):(\d+)',a)) print(res)
Output{'Nikhil': '1', 'Akshat': '2', 'Akash': '3'}
Explanation:
- re.findall(r'(\w+):(\d+)', a) extracts key-value pairs from the string a, where \w+ matches the key (letters, numbers, underscores) and \d+ matches the value (digits), returning a list of tuples.
- dict(...) converts the list of tuples into a dictionary, using the first element of each tuple as the key and the second as the value.
Using for Loop
For loop iterates through the string, splits each item into key-value pairs and constructs the dictionary by converting values to integers.
Python a = '[Nikhil:1, Akshat:2, Akash:3]' # Initialize an empty dictionary res = {} # Iterate through the string and convert to dictionary for item in a[1:-1].split(", "): key, value = item.split(":") res[key] = int(value) print(res)
Output{'Nikhil': 1, 'Akshat': 2, 'Akash': 3}
Explanation:
- a[1:-1].split(", ") removes the brackets [ ] and splits the string on ", " to get items like "Nikhil:1".
- Loop and Split Each Item: For each item, key, value = item.split(":") separates the name from the number.
- Build the Dictionary: res[key] = int(value) converts the number to an integer and stores the key-value pair in res.
Similar Reads
Convert Unicode String to Dictionary in Python Python's versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is convert
2 min read
Convert string to a list in Python Our task is to Convert string to a list in Python. Whether we need to break a string into characters or words, there are multiple efficient methods to achieve this. In this article, we'll explore these conversion techniques with simple examples. The most common way to convert a string into a list is
2 min read
Python - Convert Dictionary Object into String In Python, there are situations where we need to convert a dictionary into a string format. For example, given the dictionary {'a' : 1, 'b' : 2} the objective is to convert it into a string like "{'a' : 1, 'b' : 2}". Let's discuss different methods to achieve this:Using strThe simplest way to conver
2 min read
Python - Convert list of string to list of list In Python, we often encounter scenarios where we might have a list of strings where each string represents a series of comma-separated values, and we want to break these strings into smaller, more manageable lists. In this article, we will explore multiple methods to achieve this. Using List Compreh
3 min read
Convert String to Set in Python There are multiple ways of converting a String to a Set in python, here are some of the methods.Using set()The easiest way of converting a string to a set is by using the set() function.Example 1 : Pythons = "Geeks" print(type(s)) print(s) # Convert String to Set set_s = set(s) print(type(set_s)) pr
1 min read