This error occurs when you try to call the items()
method on a string instead of a Python dictionary. If you have a JSON string, you can parse the string to a dictionary using the json.loads()
method. For example,
import json my_dict = '{"name":"margherita", "price":7.99, "is_vegetarian":True}' parsed_obj = json.loads(my_dict) items = parsed_obj.items()
This tutorial will go through the error in detail with code examples.
Table of contents
AttributeError: ‘str’ object has no attribute ‘items’
AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘str’ object has no attribute ‘items’” tells us that the string object we handle does not have the attribute items()
.
items()
is a dictionary method that returns a view object containing the key-value pairs of the dictionary as tuples in a list.
We can check if an attribute exists for an object using the dir()
function. For example,
my_str = '{"particle":"electron", "mass":0.511, "charge":-1}' print(type(my_str)) print('items' in dir(my_str))
<class 'str'> False
We can see that items()
is not in the list of attributes for the str
object.
Example
Let’s look at an example of trying to call the items()
method on a string.
# Create string my_dict = '{"particle":"electron", "mass":0.511, "charge":-1}' # Attempt to get the items of the object dict_items = my_dict.items() print(dict_items)
Let’s run the code to see what happens:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [15], in <cell line: 4>() 1 import json 3 my_dict = '{"particle":"electron", "mass":0.511, "charge":-1}' ----> 4 dict_items = my_dict.items() 5 print(dict_items) AttributeError: 'str' object has no attribute 'items'
The error occurs because my_dict is a string, and items() is not a string method in Python.
Solution
We can solve the error by importing the json
module and calling json.loads()
to convert the JSON string into a Python dictionary. Let’s look at the revised code:
# Import json module import json # Create string my_dict = '{"particle":"electron", "mass":0.511, "charge":-1}' # Parse JSON string to Python dictionary parsed_obj = json.loads(my_dict) # Print items as list of tuples print(list(parsed_obj.items()))
Let’s run the code to get the result:
[('particle', 'electron'), ('mass', 0.511), ('charge', -1)]
Example #2
Let’s look at a second example using a POST request to httpbin.
Let’s run the code to see what happens:
# Import requests module import requests # Make a POST request to httpbin endpoint res = requests.post( 'https://httpbin.org/post', data={'name': 'pepperoni', 'price': 10.99}, headers='{"Accept": "application/json", "Content-Type": "application/json"}' ) # parse JSON response to native Python object print(res.json())
AttributeError: 'str' object has no attribute 'items'
The error occurs because the headers
keyword argument needs to be a Python dictionary not a JSON string.
Solution
We can solve the error by removing the quotes around the headers
argument so that it is a dictionary instead of a JSON string. Let’s look at the revised code:
# Import requests module import requests # Make a POST request to httpbin endpoint data = {"name": "morpheus", "job": "leader"} res = requests.post( 'https://httpbin.org/post', data=data, headers={"Accept": "application/json", "Content-Type": "application/json"} ) # parse JSON response to native Python object print(res.json())
Let’s run the code to get the JSON response.
{'args': {}, 'data': 'name=morpheus&job=leader', 'files': {}, 'form': {}, 'headers': {'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Length': '24', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.27.1', 'X-Amzn-Trace-Id': 'Root=1-62d5e3e7-292d88f61c5836a57ec1599d'}, 'json': None, 'origin': '90.206.95.191', 'url': 'https://httpbin.org/post'}
Summary
Congratulations on reading to the end of this tutorial!
For further reading on AttributeErrors with string objects, go to the articles:
- How to Solve Python AttributeError: ‘str’ object has no attribute ‘append’
- How to Solve Python AttributeError: ‘str’ object has no attribute ‘trim’
To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.