Open In App

Python - Converting list string to dictionary

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy