Last updated: Apr 9, 2024
Reading timeยท6 min
To convert a comma-separated string to a dictionary:
str.split()
method to split the string on each comma.dict()
class.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)
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.
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.
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)
The str.split() method splits the string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At 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.
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)
Alternatively, you can use a dict comprehension.
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)
Dict comprehensions are very similar to list comprehensions.
If the values in your dictionary are numbers, use the int() or float() classes to convert them.
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)
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.
To convert a dictionary to a comma-separated string:
str.keys()
or str.values()
method to get a view of the
dictionary's keys or values.str.join()
method to join the keys or values with a comma
separator.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 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.
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.
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.
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'
If you need to convert a dictionary to a comma-separated string containing the
dictionary's keys and values, use the dict.items()
method.
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 dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
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.
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.
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 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.
Alternatively, you can use the json.loads()
method.
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.
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.
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.
If your string isn't valid JSON, you can use the PyYAML
module.
First, install the module by running the pip install pyyaml command.
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.
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'>
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.
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.
To split strings in a list into key-value pairs:
dict()
class.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)
We used a generator expression to split each string in the list into a 2-element list.
# ๐๏ธ [['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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: