TypeError: can only concatenate str (not “dict”) to str (Fixed)

Updated Sep 22, 2023 ⤳ 4 min read

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 

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

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 containing error information:


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

print('error: ' + errorMessage)

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.

1. 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)

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!'}

2. 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)

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.

3. 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!

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!'}

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!'}

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

Thanks for reading!

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

`
Exit mobile version