Join the Values of a dictionary into a string in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Photo from Unsplash

Join the Values of a dictionary into a string in Python #

To join the values of a dictionary into a string:

  1. Call the str.join() method on a string separator.
  2. Call the values() method on the dict and pass the result to the join() method.
  3. The result will be a string containing the dictionary's values separated by the provided separator.
main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} values = ' '.join(map(str, my_dict.values())) print(values) # 👉️ 1 2 3 keys = ' '.join(my_dict) print(keys) # 👉️ a b c items = ' '.join(f'{key} {value}' for key, value in my_dict.items()) print(items) # 👉️ a 1 b 2 c 3

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.

This is why we used the map() function - to convert each dictionary value to a string before passing them to the join() method.

Alternatively, you can use a generator expression.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} values = ' '.join(str(val) for val in my_dict.values()) print(values) # 👉️ 1 2 3

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

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

main.py
my_dict = {'id': 1, 'name': 'Alice'} print(my_dict.values()) # 👉️ dict_values([1, 'Alice'])

If your dictionary doesn't contain integer values, you don't have to use the str() class.

main.py
my_dict = {'a': 'one', 'b': 'two', 'c': 'three'} values = ' '.join(my_dict.values()) print(values) # 👉️ "one two three"

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

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} values = '-'.join(str(val) for val in my_dict.values()) print(values) # 👉️ 1-2-3

If you need to join the dictionary's values with spaces, call the method on a string that contains a space.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} values = ' '.join(str(val) for val in my_dict.values()) print(values) # 👉️ '1 2 3'

Similarly, you can use a newline (\n) to join the values in the dict with a newline character.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} values = '\n'.join(str(val) for val in my_dict.values()) # 1 # 2 # 3 print(values)

If you don't need a separator and just want to join the dictionary's values into a string, call the join() method on an empty string.

main.py
my_dict = {'a': 1, 'b': 2, 'c': 3} values = ''.join(str(val) for val in my_dict.values()) print(values) # 👉️ '123'
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.