To define a dictionary in Python, you need to use curly brackets with the keys and values separated by colons. If you use commas between keys and values, you create a set. Then when you try to use the dictionary method items on the set, you will raise the AttributeError: ‘set’ object has no attribute ‘items’. The items method belongs to the dictionary data type and not the set data type.

To solve this error, ensure the object you are using has a dictionary structure with colons between keys and values.

This tutorial will go through the error in detail and solve it with the help of code examples.


AttributeError: ‘set’ 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 “‘set’ object has no attribute ‘items’” tells us that the set object we are handling does not have the items attribute.

The items method belongs to the dictionary data type and returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

Let’s look at an example of calling the items() method on a dictionary:

a_dict = {'margherita':7.99, 'pepperoni':8.99, 'four cheese':10.99}

print(type(a_dict))

x = a_dict.items()

print(f'Dictionary items as list:\n{list(x)}')
<class 'dict'>
Dictionary items as list:
[('margherita', 7.99), ('pepperoni', 8.99), ('four cheese', 10.99)]

If we replace the colons with commas, we will get a set instead of a dictionary. We can verify this by printing the type of object.

a_dict = {'margherita',7.99, 'pepperoni',8.99, 'four cheese',10.99}

print(type(a_dict))
<class 'set'>

Then we try to call the items() method we throw the AttributeError:

x = a_dict.items()

print(f'Dictionary items as list:\n{list(x)}')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-756f0e210815> in <module>
----> 1 x = a_dict.items()
      2 print(f'Dictionary items as list:\n{list(x)}')
AttributeError: 'set' object has no attribute 'items'

Let’s look at an example scenario in the next section.

Example: ‘set’ object has no attribute ‘items’ using requests

This error commonly occurs when incorrectly defining the headers parameter using the requests library. Let’s look at an example where we make a POST request to a webpage and specify the Content-Type in the headers dictionary.

import requests
import json
 
url = "https://httpbin.org/post"
 
headers = {"Content-Type", "application/json; charset=utf-8"}
 
data = {
    "id": 1,
    "name": "Anakin",
    "passion": "podracing",
}
 
response = requests.post(url, headers=headers, json=data)
 
print("Status Code", response.status_code)
print("JSON Response ", response.json())

Let’s run the code to see what happens:

~/opt/anaconda3/lib/python3.8/site-packages/requests/models.py in prepare_headers(self, headers)
    449         self.headers = CaseInsensitiveDict()
    450         if headers:
--> 451             for header in headers.items():
    452                 # Raise exception on invalid header value.
    453                 check_header_validity(header)
AttributeError: 'set' object has no attribute 'items'

The error occurs because the key "Content-Type" and the value "application/JSON; charset=utf-8" in the headers dictionary have a comma between them instead of a colon. Therefore, Python interprets the headers object as a set and not a dictionary.

The requests.post() has a step where it iterates through the key-value pairs in the headers object using items(). Only dictionaries have the items() method. If we pass a set instead of a dictionary to the post() function we will get the AttributeError.

Solution

We need to replace the comma with a colon between the key and the value when creating the headers object to solve this error. We will then be passing a dictionary to the post() method. Let’s look at the revised code:

import requests
import json
 
url = "https://httpbin.org/post"
 
headers = {"Content-Type": "application/json; charset=utf-8"}
 
data = {
    "id": 1,
    "name": "Anakin",
    "passion": "podracing",
}
 
response = requests.post(url, headers=headers, json=data)
 
print("Status Code", response.status_code)
print("JSON Response ", response.json())

Let’s run the code to get the response as a JSON:

Status Code 200
JSON Response  {'args': {}, 'data': '{"id": 1, "name": "Anakin", "passion": "podracing"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Length': '51', 'Content-Type': 'application/json; charset=utf-8', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.27.1', 'X-Amzn-Trace-Id': 'Root=1-62287bd0-3be4ff1a4bc5900c055384f2'}, 'json': {'id': 1, 'name': 'Anakin', 'passion': 'podracing'}, 'origin': '90.206.95.191', 'url': 'https://httpbin.org/post'}

The Status Code 200 tells us we successfully made the HTTP request and retrieved the JSON response.

Summary

Congratulations on reading to the end of this tutorial! The AttributeError: ‘set’ object has no attribute ‘items’ occurs when you call the items() method on a set. This error typically occurs when you incorrectly create a dictionary using commas between the keys and values instead of colons.

To solve this error, ensure that you use colons between keys and values.

For further reading on AttributeErrors, go to the articles:

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!