Skip to main content

How to Join Dictionary Keys or Values into a String in Python

Often, you need to represent the keys or values (or both) from a Python dictionary as a single, formatted string, typically with a specific separator between the elements. Python's str.join() method provides an efficient and idiomatic way to achieve this.

This guide demonstrates how to join dictionary keys and values into strings, including how to handle non-string elements correctly.

The Goal: Concatenating Dictionary Contents

Given a dictionary, we want to create a single string that combines either all its keys or all its values, separated by a chosen character or string (like a comma, space, newline, etc.).

Example Data:

# Example 1: String values
string_dict = {'site': 'tutorialereference', 'tld': '.com', 'topic': 'python'}

# Example 2: Mixed-type values
mixed_dict = {'name': 'Alice', 'id': 101, 'active': True, 'score': 95.5}

# Example 3: Mixed-type keys
key_dict = {1: 'one', 'two': 2, 3.0: 'three'}

Joining Dictionary VALUES into a String

Using str.join() with dict.values()

The dict.values() method returns a view object containing the dictionary's values. You can pass this directly to separator.join(), provided all values are already strings.

string_dict = {'site': 'tutorialreference', 'tld': '.com', 'topic': 'python'}

# Join string values with a space separator
separator = ' '
values_string = separator.join(string_dict.values())

print(f"Dictionary: {string_dict}")
print(f"Values view: {string_dict.values()}")
print(f"Joined values ('{separator}' separator): '{values_string}'")

Output:

Dictionary: {'site': 'tutorialreference', 'tld': '.com', 'topic': 'python'}
Values view: dict_values(['tutorialreference', '.com', 'python'])
Joined values (' ' separator): 'tutorialreference .com python'
  • string_dict.values(): Gets an iterable view of the values ('tutorialreference', '.com', 'python').
  • ' '.join(...): Concatenates the elements from the view, placing a space between each one.

Handling Non-String Values (TypeError)

str.join() requires all elements in the iterable to be strings. If your dictionary values include numbers, booleans, or other types, passing my_dict.values() directly to join() will raise a TypeError.

mixed_dict = {'name': 'Alice', 'id': 101, 'active': True, 'score': 95.5}
separator = ', '

try:
# ⛔️ TypeError: sequence item 1: expected str instance, int found
# (Error occurs because 101, True, 95.5 are not strings)
values_string = separator.join(mixed_dict.values())
print(values_string)
except TypeError as e:
print(f"Caught TypeError: {e}")

Solution: Using map(str, ...)

Convert all values to strings before joining using the map() function. map(str, iterable) applies the str() function to each item in the iterable.

mixed_dict = {'name': 'Alice', 'id': 101, 'active': True, 'score': 95.5}
separator = ', '

# Use map(str, ...) to convert all values to strings first
values_iterator = map(str, mixed_dict.values())
values_string = separator.join(values_iterator)

print(f"\nDictionary: {mixed_dict}")
print(f"Joined values (map, '{separator}' separator): '{values_string}'")
# Output: Joined values (map, ', ' separator): 'Alice, 101, True, 95.5'

This is a concise way to handle mixed types.

Solution: Using a Generator Expression (str(v) for v in ...)

A generator expression achieves the same result as map(str, ...) and is often considered equally or more Pythonic.

mixed_dict = {'name': 'Alice', 'id': 101, 'active': True, 'score': 95.5}
separator = ' | '

# Use a generator expression to convert values to strings
values_string = separator.join(str(value) for value in mixed_dict.values())

print(f"\nDictionary: {mixed_dict}")
print(f"Joined values (genexpr, '{separator}' separator): '{values_string}'")
# Output: Joined values (genexpr, ' | ' separator): 'Alice | 101 | True | 95.5'

Examples with Different Separators

Choose the string you call .join() on to control the separator.

mixed_dict = {'name': 'Alice', 'id': 101}

# Comma separator
print(','.join(str(v) for v in mixed_dict.values()))
# Output: Alice,101

# Newline separator
print('\n'.join(str(v) for v in mixed_dict.values()))
# Output:
# Alice
# 101

# No separator (direct concatenation)
print(''.join(str(v) for v in mixed_dict.values()))
# Output: Alice101

Joining Dictionary KEYS into a String

Using str.join() with dict (Iterates Keys)

Iterating directly over a dictionary (for key in my_dict: ...) yields its keys. Therefore, you can pass the dictionary itself directly to separator.join(), if all keys are strings.

string_dict = {'site': 'tutorialreference', 'tld': '.com', 'topic': 'python'}
separator = ' - '

# Pass the dictionary directly to join() (iterates keys)
keys_string = separator.join(string_dict)

print(f"\nDictionary: {string_dict}")
print(f"Joined keys ('{separator}' separator): '{keys_string}'")
# Output: Joined keys (' - ' separator): 'site - tld - topic'

# Explicitly using .keys() works identically:
# keys_string_explicit = separator.join(string_dict.keys())
# print(f"Joined keys (explicit .keys()): '{keys_string_explicit}'")

Handling Non-String Keys

If your dictionary keys are not all strings (e.g., integers, floats), you must convert them to strings before joining, just like with values.

key_dict = {1: 'one', 'two': 2, 3.0: 'three'}
separator = ' | '

# Error scenario (keys are not all strings)
try:
# ⛔️ TypeError: sequence item 0: expected str instance, int found
keys_string_error = separator.join(key_dict)
print(keys_string_error)
except TypeError as e:
print(f"\nCaught TypeError (non-string keys): {e}")


# Solution: Use map(str, ...) or a generator expression
keys_string_fixed = separator.join(str(key) for key in key_dict)
# Or: keys_string_fixed = separator.join(map(str, key_dict))

print(f"\nDictionary with mixed key types: {key_dict}")
print(f"Joined keys (fixed, '{separator}' separator): '{keys_string_fixed}'")
# Output: Joined keys (fixed, ' | ' separator): '1 | two | 3.0'

Examples with Different Separators

Works the same as with values.

string_dict = {'site': 'tutorialreference', 'tld': '.com', 'topic': 'python'}

print('\n'.join(string_dict)) # Newline separator
# Output:
# site
# tld
# topic

print(''.join(string_dict)) # No separator
# Output: sitetldtopic

Joining Dictionary ITEMS (Key-Value Pairs) into a String

If you want a string representing both keys and values (e.g., "key1=value1,key2=value2"), you first need to format each key-value pair into a string and then join those strings.

mixed_dict = {'name': 'Alice', 'id': 101, 'active': True}
pair_separator = '; '
kv_separator = ':'

# Format each item, then join
items_string = pair_separator.join(
f"{str(key)}{kv_separator}{str(value)}" # Format key:value, ensure both are strings
for key, value in mixed_dict.items() # Iterate through (key, value) pairs
)

print(f"\nDictionary: {mixed_dict}")
print(f"Joined items ('{pair_separator}' separator): '{items_string}'")
# Output: Joined items ('; ' separator): 'name:Alice; id:101; active:True'
  • mixed_dict.items(): Provides an iterable view of (key, value) tuples.
  • f"{str(key)}{kv_separator}{str(value)}": An f-string formats each pair. str() ensures both key and value are strings before formatting.
  • pair_separator.join(...): Joins the formatted "key:value" strings.

Conclusion

Python's str.join() method is the standard tool for concatenating elements from an iterable into a string with a specific separator.

  • To join dictionary values: Use separator.join(str(v) for v in my_dict.values()) or separator.join(map(str, my_dict.values())). Remember to convert non-string values using str().
  • To join dictionary keys: Use separator.join(str(k) for k in my_dict) or separator.join(map(str, my_dict)). Convert non-string keys using str(). Iterating directly over the dictionary (join(my_dict)) works if all keys are strings.
  • To join dictionary items: First, format each (key, value) pair into a single string (e.g., using an f-string and str()), then use join() on the resulting list or generator of formatted strings.

Always handle potential non-string elements by converting them to strings before passing them to join() to avoid TypeError.