The error "TypeError: write() argument must be str, not dict" occurs when you pass a dictionary to the write()
method in Python. The error might occur when you accidentally passed the whole dictionary instead of a specific key in the dictionary to the write()
method. Or if you intended to pass the dictionary itself, you need to convert the dictionary to a string.
Problem
Here is an example of the code in which the error occurs:
with open('sample.txt', 'w', encoding='utf-8') as file:
dict = {'site': 'Sharooq', 'language': "python"}
file.write(dict)
Here we passed the "dict" object directly to the write()
method. This will result in the error mentioned above.
Solutions
1, Convert the dictionary to a string
You can use the str()
method to convert the dictionary object into a string and pass it to the write()
method as shown in the following code.
with open('sample.txt', 'w', encoding='utf-8') as file:
dict = {'site': 'Sharooq', 'language': "python"}
file.write(str(dict))
The output file is as follows:
{'site': 'Sharooq', 'language': 'python'}
2, Convert the dictionary to a JSON string using json.dumps()
You can convert the dictionary to a JSON string using json.dumps() method. The following code demonstrates the same:
import json
with open('sample.txt', 'w', encoding='utf-8') as file:
dict = {'site': 'Sharooq', 'language': "python"}
file.write(json.dumps(dict))
The output file will be in a JSON formatted string as follows:
{"site": "Sharooq", "language": "python"}
3, Accessing a specific key in the dictionary
If you meant to output a specific value to a key in the dictionary, you can follow the following code:
with open('sample.txt', 'w', encoding='utf-8') as file:
dict = {'site': 'Sharooq', 'language': "python"}
file.write(str(dict["site"]))
The output will be as following:
Sharooq
The value of the key we are accessing in the dictionary needs to be a string. The write()
method only accepts a string as its argument.
How to check the type of a value in the dictionary?
You can use the built-in type()
or isinstace()
method to check the type of a value.
dict = {'site': 'Sharooq', 'language': "python"}
print(type(dict["site"]))
print(isinstance(dict["site"], str))
The type()
method returns the type of a given object.
The isinstance()
method takes two arguments. First, the actual value and the second, a type. If the value matches the type, it will return "True".
I hope this was helpful to you. You can visit the feature articles section to find interesting topics. See you in the next one.