TypeError: write() argument must be str, not dict (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: write() argument must be str, not dict (Python) #

The Python "TypeError: write() argument must be str, not dict" occurs when we pass a dictionary to the write() method. To solve the error, convert the dictionary to a string or access a specific key in the dictionary that has a string value.

typeerror write argument must be str not dict

Here is an example of how the error occurs.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_dict = {'name': 'Alice', 'age': 30} # ⛔️ TypeError: write() argument must be str, not dict my_file.write(my_dict)
We passed a dict object to the write() method, but the method can only be called with a string argument.

One way to solve the error is to convert the dictionary to a string.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_dict = {'name': 'Alice', 'age': 30} my_file.write(str(my_dict)) # 👉️ {'name': 'Alice', 'age': 30}

You can also convert the dictionary to a JSON string by using the json.dumps method.

main.py
import json with open('example.txt', 'w', encoding='utf-8') as my_file: my_dict = {'name': 'Alice', 'age': 30} my_file.write(json.dumps(my_dict)) # 👉️ {"name": "Alice", "age": 30}

The json.dumps method converts a Python object to a JSON formatted string.

If you meant to access a specific key in the dictionary, use square brackets.

main.py
with open('example.txt', 'w', encoding='utf-8') as my_file: my_dict = {'name': 'Alice', 'age': 30} my_file.write(my_dict['name']) # 👉️ Alice
Make sure that the key you are accessing has a value of type string because the write() method can only get called with a string argument.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_dict = {'name': 'Alice'} print(type(my_dict)) # 👉️ <class 'dict'> print(isinstance(my_dict, dict)) # 👉️ True my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

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.