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
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’

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.