Undefined error dict object has no attribute
Reading time В· 3 min
AttributeError: ‘dict’ object has no attribute in Python #
The Python «AttributeError: ‘dict’ object has no attribute» occurs when we use dot notation instead of bracket notation to access a key in a dictionary. To solve the error, use bracket notation when accessing the key, e.g. my_dict[‘age’] .
Here is an example of how the error occurs.
If you are trying to access a key in a dictionary, use bracket notation.
The get() method doesn’t raise a KeyError if the key is not present in the dictionary.
If you are trying to add key-value pairs to a dictionary, use bracket notation.
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.
If you need to iterate over a dictionary, use the items() method.
Make sure you aren’t reassigning the value of your variable somewhere in your code.
We set the value of the my_list variable to a list initially, but we set it to a dictionary later on, which caused the error.
If you need to check whether an object contains an attribute, use the hasattr function.
The hasattr function takes the following 2 parameters:
|object||The object we want to test for the existence of the attribute|
|name||The name of the attribute to check for in the object|
The hasattr() function returns True if the string is the name of one of the object’s attributes, otherwise False is returned.
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.
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».