Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
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.
Here is an example of how the error occurs.
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)
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.
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.
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.
with open('example.txt', 'w', encoding='utf-8') as my_file: my_dict = {'name': 'Alice', 'age': 30} my_file.write(my_dict['name']) # 👉️ Alice
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.
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.