Join the Keys of a dictionary into a string in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Photo from Unsplash

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

To join the keys of a dictionary into a string:

  1. Call the str.join() method on a string separator.
  2. Pass the dictionary to the join() method.
  3. The result will be a string containing the dictionary's keys separated by the provided separator.
main.py
my_dict = {'name': 'Alice', 'country': 'Austria', 'job': 'accountant'} keys = ', '.join(my_dict) print(keys) # 👉️ 'name, country, job' values = ', '.join(my_dict.values()) print(values) # 👉️ Alice, Austria, accountant items = ', '.join(f'{key} {value}' for key, value in my_dict.items()) print(items) # 👉️ name Alice, country Austria, job accountant

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 dictionary contains integer keys (or other types), convert them to strings before calling join().

main.py
my_dict = {'name': 'Alice', 'country': 'Austria', 'job': 'accountant', 100: 200} keys = ', '.join(map(str, my_dict)) print(keys) # 👉️ 'name, country, job, 100' values = ', '.join(map(str, my_dict.values())) print(values) # 👉️ Alice, Austria, accountant, 200 items = ', '.join(f'{key} {value}' for key, value in my_dict.items()) print(items) # 👉️ name Alice, country Austria, job accountant, 100 200

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

We used the function to convert each key and value in the dictionary to a string, before passing them to the str.join() method.

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

main.py
my_dict = {'name': 'Alice', 'country': 'Austria', 'job': 'accountant'} keys = '-'.join(my_dict) print(keys) # 👉️ 'name-country-job'

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

main.py
my_dict = {'name': 'Alice', 'country': 'Austria', 'job': 'accountant'} keys = ' '.join(my_dict) print(keys) # 👉️ 'name country job'

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

main.py
my_dict = {'name': 'Alice', 'country': 'Austria', 'job': 'accountant'} keys = '\n'.join(my_dict) # name # country # job print(keys)

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

main.py
my_dict = {'name': 'Alice', 'country': 'Austria', 'job': 'accountant'} keys = ''.join(my_dict) print(keys) # 👉️ 'namecountryjob'
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.