How to fix "can only concatenate str (not “dict”) to str" in Python
Tags: python, programming
Published: 2023-02-03 20:12:16

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-dict-to-str-fix) 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 
```

## Why does it happen?

Python as a [Strongly-typed programming language](https://www.decodingweb.dev/how-to-learn-a-programming-language#type-systems) 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:

```python
# ⛔ 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. <u>Use an f-string</u>
2. <u>Use printf-style formatting</u>
3. <u>Access dictionary values by key</u>
4. <u>Use `print()` with multiple arguments - ideal for debugging</u>

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:

```python
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:

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

print(f'Error: {error}')
# output: Error: {'code': 401, 'message': 'Access denied!'}
```

**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:

```python
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.

**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:

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

print('Error: ' + error['message'])
# output: Error: Access denied!
```

**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.

```python
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:

```python
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!

**❤️ You might like:**

- [TypeError: can only concatenate str (not "list") to str (Fixed)](https://www.decodingweb.dev/python-typeerror-can-only-concatenate-str-not-list-to-str-fix)
- [Not all arguments converted during string formatting error in Python (Fixed)](https://www.decodingweb.dev/python-typeerror-not-all-arguments-converted-during-string-formatting-fix)
- [TabError: inconsistent use of tabs and spaces in indentation (Python)](https://www.decodingweb.dev/python-taberror-inconsistent-use-of-tabs-and-spaces-in-indentation-fix)
- [How to fix the "TypeError: unhashable type: 'dict'" error in Python](https://www.decodingweb.dev/python-typeerror-unhashable-type-dict-fixed)
- [How to reverse a range in Python (with examples)](https://www.decodingweb.dev/reverse-a-range-in-python)
- [TypeError: missing 1 required positional argument: 'self' (Fixed)](https://www.decodingweb.dev/python-typeerror-missing-1-required-positional-argument-self)
- [Unindent does not match any outer indentation level error in Python (Fixed)](https://www.decodingweb.dev/python-indentationerror-unindent-does-not-match-any-outer-indentation-level-fix)