Convert a comma-separated String to a Dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
6 min

banner

# Table of Contents

  1. Convert a comma-separated String to a Dictionary in Python
  2. Convert a Dictionary to a comma-separated String in Python
  3. Convert string representation of Dict to Dict in Python
  4. Split strings in a List into key-value pairs (dict) in Python

# Convert a comma-separated String to a Dictionary in Python

To convert a comma-separated string to a dictionary:

  1. Use the str.split() method to split the string on each comma.
  2. Split each string in the list on the delimiter between the key-value pairs.
  3. Pass the results to the dict() class.
main.py
my_str = "name=Bobbby,country=Austria,language=German" my_dict = dict(item.split('=') for item in my_str.split(',')) # ๐Ÿ‘‡๏ธ {'name': 'Bobbby', 'country': 'Austria', 'language': 'German'} print(my_dict)

convert comma separated string to dictionary

The code for this article is available on GitHub

The example uses the dict() class to convert a comma-separated string to a dictionary.

The first step is to split the string on each comma, semi-colon or any other character that separates the key-value pairs.

main.py
my_str = "name=Bobby,country=Austria,language=German" # ๐Ÿ‘‡๏ธ ['name=Bobby', 'country=Austria', 'language=German'] print(my_str.split(','))

The next step is to use a generator expression to iterate over the list and split each string on the character that separates the keys and values.

main.py
my_str = "name=Bobby,country=Austria,language=German" my_dict = dict(item.split('=') for item in my_str.split(',')) # ๐Ÿ‘‡๏ธ {'name': 'Bobby', 'country': 'Austria', 'language': 'German'} print(my_dict)
Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If the keys and values in your string are separated by colons, make sure to update the separator in the call to the str.split() method.

main.py
my_str = "name:Bobby,country:Austria,language:German" my_dict = dict(item.split(':') for item in my_str.split(',')) # ๐Ÿ‘‡๏ธ {'name': 'Bobby', 'country': 'Austria', 'language': 'German'} print(my_dict)

# Convert a comma-separated String to a Dictionary using a dict comprehension

Alternatively, you can use a dict comprehension.

main.py
my_str = "name=Bobby,country=Austria,language=German" my_dict = {key: value for key, value in [item.split( '=') for item in my_str.split(',')]} # ๐Ÿ‘‡๏ธ {'name': 'Bobby', 'country': 'Austria', 'language': 'German'} print(my_dict)

convert comma separated string to dictionary using dict comprehension

The code for this article is available on GitHub

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

# Convert numeric values to integers or floats

If the values in your dictionary are numbers, use the int() or float() classes to convert them.

main.py
my_str = "x=0.95,y=4.55" my_dict = { key: float(value) for key, value in [item.split('=') for item in my_str.split(',')] } # ๐Ÿ‘‡๏ธ {'x': 0.95, 'y': 4.55} print(my_dict)

convert numeric values to integers or floats

The code for this article is available on GitHub

We used the float() class to convert each value to a floating-point number.

You would use the int() class if you need to convert numeric values to integers.

# Convert a Dictionary to a comma-separated String in Python

To convert a dictionary to a comma-separated string:

  1. Use the str.keys() or str.values() method to get a view of the dictionary's keys or values.
  2. Use the str.join() method to join the keys or values with a comma separator.
main.py
my_dict = {'name': 'Bobby', 'age': 30, 'salary': 100} # โœ… Convert a dictionary's keys to a comma-separated string keys_str = ','.join(my_dict.keys()) print(keys_str) # ๐Ÿ‘‰๏ธ 'name,age,salary' # --------------------------------------------- # โœ… Convert a dictionary's values to a comma-separated string values_str = ','.join(str(value) for value in my_dict.values()) print(values_str) # ๐Ÿ‘‰๏ธ 'Bobby,30,100'
The code for this article is available on GitHub

The example uses the dict.keys() method to get a view of the dictionary's keys.

The dict.keys() method returns a new view of the dictionary's keys.

The dict.values() method returns a new view of the dictionary's values.

The last step is to use the str.join() method to join the dictionary's keys or values into a string with a comma separator.

main.py
my_dict = {'name': 'Bobby', 'age': 30, 'salary': 100} keys_str = ','.join(my_dict.keys()) print(keys_str) # ๐Ÿ‘‰๏ธ 'name,age,salary' values_str = ','.join(str(value) for value in my_dict.values()) print(values_str) # ๐Ÿ‘‰๏ธ 'Bobby,30,100'

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

If your iterable contains numbers or other types, convert all of the values to string before calling join().

The string the method is called on is used as the separator between the elements.

We used a comma in the examples. If you need to separate the values with a comma followed by a space, make sure to adjust the string the method is called on.

main.py
my_dict = {'name': 'Bobby', 'age': 30, 'salary': 100} keys_str = ', '.join(my_dict.keys()) print(keys_str) # ๐Ÿ‘‰๏ธ 'name, age, salary' values_str = ', '.join(str(value) for value in my_dict.values()) print(values_str) # ๐Ÿ‘‰๏ธ 'Bobby, 30, 100'

# Convert a dictionary's items to a comma-separated string

If you need to convert a dictionary to a comma-separated string containing the dictionary's keys and values, use the dict.items() method.

main.py
my_dict = {'name': 'Bobby', 'age': 30, 'salary': 100} dict_str = ", ".join("=".join([key, str(value)]) for key, value in my_dict.items()) print(dict_str) # ๐Ÿ‘‰๏ธ name=Bobby, age=30, salary=100
The code for this article is available on GitHub

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'name': 'Bobby', 'age': 30, 'salary': 100} # ๐Ÿ‘‡๏ธ dict_items([('name', 'Bobby'), ('age', 30), ('salary', 100)]) print(my_dict.items())

We used the join() method to join each key-value pair with an equal sign separator and then used the join() method again to join the key-value pairs with a comma-separator.

# Convert string representation of Dict to Dict in Python

Use the ast.literal_eval() method to convert the string representation of a dictionary to a dictionary.

The ast.literal_eval() method allows us to safely evaluate a string that contains a Python literal.

main.py
from ast import literal_eval import json my_str = '{"id": 0, "name": "Bobby", "salary": 100}' my_dict = literal_eval(my_str) print(my_dict) # ๐Ÿ‘‰๏ธ {'id': 0, 'name': 'Bobby', 'salary': 100} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>
The code for this article is available on GitHub

The example uses the ast.literal_eval() method to convert the string representation of a dictionary to an actual dictionary.

The ast.literal_eval() method allows us to safely evaluate a string that contains a Python literal.

The string may consist of strings, bytes, numbers, tuples, lists, dictionaries, sets, booleans and None.

# Convert string representation of Dict to Dict using json.loads()

Alternatively, you can use the json.loads() method.

main.py
import json my_str = '{"id": 0, "name": "Bobby", "salary": 100}' my_dict = json.loads(my_str) print(my_dict) # ๐Ÿ‘‰๏ธ {'id': 0, 'name': 'Bobby', 'salary': 100} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

We used the json.loads() method to parse the string representation of a dictionary to a native dict object.

Note that the json.loads() method can only be used if you have a valid JSON string.

For example, the keys and values have to be double-quoted. This wouldn't work if the keys or values are wrapped in single quotes.

The json.loads() method parses a JSON string into a native Python object.

main.py
import json json_str = '{"name": "Bobby", "age": 30}' my_dict = json.loads(json_str) print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

If the data being parsed is not a valid JSON string, a JSONDecodeError is raised.

# Convert string representation of Dict to Dict using PyYAML

If your string isn't valid JSON, you can use the PyYAML module.

First, install the module by running the pip install pyyaml command.

shell
pip install pyyaml # ๐Ÿ‘‡๏ธ or with pip3 pip3 install pyyaml

Now you can import the module and use it to parse the string into a native Python dictionary.

main.py
import yaml my_str = "{'id': 0, 'name': 'Bobby', 'salary': 100}" my_dict = yaml.full_load(my_str) print(my_dict) # ๐Ÿ‘‰๏ธ {'id': 0, 'name': 'Bobby', 'salary': 100} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>
The code for this article is available on GitHub
The yaml.full_load() method takes a YAML document, parses it and produces the corresponding Python object.

Note that using the full_load() method with untrusted input is not recommended.

If you're working with untrusted data, use the yaml.safe_load() method instead.

main.py
import yaml my_str = "{'id': 0, 'name': 'Bobby', 'salary': 100}" my_dict = yaml.safe_load(my_str) print(my_dict) # ๐Ÿ‘‰๏ธ {'id': 0, 'name': 'Bobby', 'salary': 100} print(type(my_dict)) # ๐Ÿ‘‰๏ธ <class 'dict'>

The yaml.safe_load() method loads a subset of the YAML language. This is recommended for loading untrusted input.

# Split strings in a List into key-value pairs (dict) in Python

To split strings in a list into key-value pairs:

  1. Use a generator expression to split the strings in the list into nested lists of key-value pairs.
  2. Pass the two-dimensional list to the dict() class.
main.py
my_list = ['name=Bobby', 'country=Austria', 'job=accountant'] result = dict(kv.split('=') for kv in my_list) # ๐Ÿ‘‡๏ธ {'name': 'Bobby', 'country': 'Austria', 'job': 'accountant'} print(result)
The code for this article is available on GitHub

We used a generator expression to split each string in the list into a 2-element list.

main.py
# ๐Ÿ‘‡๏ธ [['name', 'Bobby'], ['country', 'Austria'], ['job', 'accountant']] print(list(kv.split('=') for kv in my_list))

The first item in each nested list is the name, and the second is the value.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

The dict() class can be passed an iterable of keyword arguments and returns a new dictionary.

If the values in your dictionary are integers, you can convert them using the int() class.

main.py
my_list = ['name=1', 'country=2', 'job=3'] def convert_to_int(kv): return (kv[0], int(kv[1])) result = dict(convert_to_int(kv.split('=')) for kv in my_list) # ๐Ÿ‘‡๏ธ {'name': 1, 'country': 2, 'job': 3} print(result)

The convert_to_int function gets called with a list containing 2 items - a key and a value.

It returns a tuple containing the key and the integer version of the value.

I've also written an article on how to convert bytes to a dictionary.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev