Python - Converting list string to dictionary
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.
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)
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.
Table of Content
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().
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)
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.
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)
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.
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)
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.