VOOZH about

URL: https://www.geeksforgeeks.org/python/python-convert-key-value-pair-comma-separated-string-into-dictionary/

⇱ Convert key-value pair comma separated string into dictionary - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert key-value pair comma separated string into dictionary - Python

Last Updated : 11 Jul, 2025

In Python, we might have a string containing key-value pairs separated by commas, where the key and value are separated by a colon (e.g., "a:1,b:2,c:3"). The task is to convert this string into a dictionary where each key-value pair is represented properly. Let's explore different ways to achieve this.

Using Dictionary Comprehension with split

This method uses dictionary comprehension to split the string and create a dictionary.


Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • The string is split by commas to get individual key-value pairs.
  • Each pair is further split by a colon to separate the key and value.
  • Dictionary comprehension creates a dictionary with the key and integer-converted value.

Let's explore some more ways and see how we can convert key-value pair comma separated string into dictionary.

Using map() with split

This method uses map() and split to process the string and convert it into a dictionary.


Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • The string is split by commas into a list of key-value pairs.
  • map() applies a lambda function to split each pair by a colon and convert the value to an integer.
  • The dict() function creates a dictionary from the mapped pairs.

Using For Loop

This method uses a simple for loop to build the dictionary.


Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • The string is split by commas to get the key-value pairs.
  • Each pair is split by a colon to separate the key and value.
  • The key-value pair is added to the dictionary after converting the value to an integer.

Using Regular Expressions

This method uses the re module to extract key-value pairs from the string.


Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • A regular expression matches key-value pairs in the string.
  • re.findall() returns a list of tuples containing the keys and values.
  • A dictionary comprehension converts the tuples into a dictionary, with the values cast to integers.
Comment