How to Fix AttributeError: ‘dict’ object has no attribute ‘add’

Diagram of dic object has no attribute add

Diagram

AttributeError: ‘dict’ object has no attribute: ‘add’ error typically occurs when you try to call the add method on a dictionary object, but the add() method does not exist for dictionaries.

Reproduce the error

main_dict = {
  'key1': 'value1',
  'key2': 'value2'
}
new_dict = {'key3': 'value3'}

main_dict.add(new_dict)
print(updated_dict)

Output

AttributeError 'dict' object has no attribute 'add'

Here’s how to fix the key-value pair to a dictionary:

Solution 1: Using the update() Method

To fix the error, you can use the “update()” method to merge two dictionaries.

main_dict = {
  'key1': 'value1',
  'key2': 'value2'
}
new_dict = {'key3': 'value3'}

main_dict.update(new_dict)
print(main_dict)

Output

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Solution 2: Using Square Bracket Notation

You can also use square brackets([]) to add or update a key-value pair in a dictionary:

main_dict = {
  'key1': 'value1',
  'key2': 'value2'
}
main_dict['key3'] = 'value3'

print(main_dict)

Output

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

And we got the same output and fixed the error.

To add elements to a dictionary, use the “dict.update()” or “square brackets” notation.

Related posts

AttributeError: ‘dict’ object has no attribute ‘id’

AttributeError: ‘dict’ object has no attribute ‘replace’

AttributeError: ‘dict’ object has no attribute ‘headers’

AttributeError: ‘dict’ object has no attribute ‘encode’

AttributeError: ‘dict’ object has no attribute ‘iteritems’

AttributeError: ‘dict’ object has no attribute ‘has_key’

AttributeError: ‘dict’ object has no attribute ‘read’

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.