AttributeError: 'dict' object has no attribute 'add'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'dict' object has no attribute 'add' #

The Python "AttributeError: 'dict' object has no attribute 'add'" occurs when we try to call the add() method on a dictionary instead of a set object. To solve the error, use the set() constructor to create an empty set, e.g. my_set = set().

attributeerror dict object has no attribute add

Here is an example of how the error occurs.

main.py
# 👇️ this is a dictionary my_set = {} print(type(my_set)) # 👉️ <class 'dict'> # ⛔️ AttributeError: 'dict' object has no attribute 'add' my_set.add('hello')

When we use empty curly braces {}, we actually create a dictionary and dictionaries don't have an add() method.

Use the set() constructor to create an empty set object.

main.py
my_set = set() my_set.add('a') my_set.add('b') my_set.add('a') print(my_set) # 👉️ {'a', 'b'}

The set.add method adds the provided element to the set.

Make sure you aren't reassigning a set to a dictionary somewhere in your code before you call add.

main.py
my_set = set() # 👇️ reassigned set to dictionary by mistake my_set = {} # ⛔️ AttributeError: 'dict' object has no attribute 'add' my_set.add('a')

We stored a set object in the variable initially, but we later set it to a dict object which caused the error.

The syntax for set comprehensions looks like:

main.py
my_list = ['a', 'b', 'c', 'a'] # 👇️ set comprehension my_set = {element for element in my_list} print(my_set) # 👉️ {'b', 'c', 'a'}

If you are trying to add a key-value pair to a dictionary, use bracket notation.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ✅ add key-value pairs to dict my_dict['country'] = 'Austria' my_dict['prof'] = 'programmer' # {'name': 'Alice', 'age': 30, 'country': 'Austria', 'prof': 'programmer'} print(my_dict) print(my_dict['country']) # 👉️ Austria
The bracket notation syntax can be used to both access the value of a key and set or update the value for a specific key.

A good way to start debugging is to print(dir(your_object)) and see what attributes a dictionary has.

Here is an example of what printing the attributes of a dict looks like.

main.py
my_dict = {'name': 'Alice', 'age': 30} # [...'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', # 'pop', 'popitem', 'setdefault', 'update', 'values' ...] print(dir(my_dict))

If you pass a class to the dir() function, it returns a list of names of the class's attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: 'dict' object has no attribute error".

Since dict objects don't have an add() method, the error is caused.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.