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.
Here is an example of the code in which the error occurs:
Here we passed the "dict" object directly to the
write() method. This will result in the error mentioned above.
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.
The output file is as follows:
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:
The output file will be in a JSON formatted string as follows:
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:
The output will be as following:
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
isinstace() method to check the type of a value.
type() method returns the type of a given object.
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.