Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Converting list string to dictionary
Next article icon

Python - Converting list string to dictionary

Last Updated : 15 Jan, 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.

Table of Content

  • Using ast.literal_eval
  • Using re.findall()
  • Using for Loop

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.

Next Article
Python - Converting list string to dictionary

M

manjeet_04
Improve
Article Tags :
  • Python
  • python-list
  • python-string
  • Python list-programs
Practice Tags :
  • python
  • python-list

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences