DEV Community

Cover image for How to fix "can only concatenate str (not “dict”) to str" in Python
Reza Lavarian
Reza Lavarian

Posted on Originally published at decodingweb.dev

How to fix "can only concatenate str (not “dict”) to str" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The Python error “TypeError: can only concatenate str (not “dict”) to str” occurs if you concatenate a string with a dictionary (dict object).

Here’s what the error looks like on Python 3:

File "/dwd/sandbox/test.py", line 6, in 
  print('error: ' + errorMessage)
     ~~~~~~~~~~^~~~~~~~~~~~~~
TypeError: can only concatenate str (not "dict") to str 
Enter fullscreen mode Exit fullscreen mode

Why does it happen?

Python as a Strongly-typed programming language doesn't allow some operations on specific data types. For instance, you can't divide 20 by '4' (because '4' is a string value) - depending on the operation, the error messages might vary.

Now, if you try to concatenate a string literal with a dict object, you'll get the "TypeError: can only concatenate str (not "dict") to str". The following code tries to concatenate the string 'error:' with a dictionary:

# ⛔ Raises TypeError: can only concatenate str (not "dict") to str
errorMessage = {
    'code': 401,
    'message': 'Access denied!' 
}

print('error: ' + errorMessage)
Enter fullscreen mode Exit fullscreen mode

How to fix TypeError: can only concatenate str (not "dict") to str

If you need to use the + operator, ensure the operands on either side are compatible. Remember: birds of a feather flock together 🦜 + 🦜.

A quick fix would be converting the dict object to a string with the str() function.

But if you want to insert dictionary values into a string, you'll have several options:

  1. Use an f-string
  2. Use printf-style formatting
  3. Access dictionary values by key
  4. Use print() with multiple arguments - ideal for debugging

Let's explore each method with examples.

Use an f-string: Formatted string literals (a.k.a f-strings) are a robust way of inserting values of a dict object into a string (in a pair of curly brackets {}).

You create an f-string by prefixing it with f or F and writing expressions inside curly braces:

error = {
    'code': 401,
    'message': 'Access denied!' 
}

print(f'Error: {error[message]} (code: {error[code]})')
# output: Error: Access denied! (code: 401)
Enter fullscreen mode Exit fullscreen mode

You can also put the main dict object inside an f-string, if you're debugging your code:

error = {
    'code': 401,
    'message': 'Access denied!' 
}

print(f'Error: {error}')
# output: Error: {'code': 401, 'message': 'Access denied!'}
Enter fullscreen mode Exit fullscreen mode

Use printf-style formatting: If you prefer to use the old-style string formatting (string % values), you can do so by passing the dictionary values as a tuple like so:

error = {
    'code': 401,
    'message': 'Access denied!' 
}

print('Error: %s (code: %s)' % (error['message'], error['code']))
# output: Error: Access denied! (code: 401)
Enter fullscreen mode Exit fullscreen mode

When using the old-style formatting, ensure the format string is valid. Otherwise, you'll get another type error: not all arguments converted during string formatting.

Access dictionary values by key: Sometimes, you need to concatenate a string value with a dictionary value, but you use the whole dict object by mistake.

In that case, you need to access the dictionary value by its key:

error = {
    'code': 401,
    'message': 'Access denied!' 
}

print('Error: ' + error['message'])
# output: Error: Access denied!
Enter fullscreen mode Exit fullscreen mode

Use print() with multiple arguments - ideal for debugging: If you're concatenating a string with a dict object and readability isn't a concern, you can pass the string and the dictionary as separate arguments to the print() function.

All the positional arguments passed to the print() function are automatically converted to strings - like how str() works.

error = {
    'code': 401,
    'message': 'Access denied!' 
}

print('Error:', error)
# output: Error: {'code': 401, 'message': 'Access denied!'}
Enter fullscreen mode Exit fullscreen mode

The print() function outputs the arguments separated by a space. You can also change the separator via the sep keyword argument.

If you need to generate the string without printing the results, you can use the str() function:

error = {
    'code': 401,
    'message': 'Access denied!' 
}

output = 'Error: ' + str(error)

print(output)
# output: Error: {'code': 401, 'message': 'Access denied!'}
Enter fullscreen mode Exit fullscreen mode

Alright, I think that does it! I hope this quick guide helped you fix your problem.

Thanks for reading!

❤️ You might like:

Top comments (0)