Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "AttributeError: 'dict' object has no attribute 'id'" occurs when
we use dot notation instead of bracket notation to access the id
key in a
dictionary. To solve the error, use bracket notation when accessing the key,
e.g. my_dict['id']
.
Here is an example of how the error occurs.
my_dict = {'id': 1, 'name': 'Alice'} # ⛔️ AttributeError: 'dict' object has no attribute 'id' print(my_dict.id)
Use bracket notation to access keys in in the dictionary.
my_dict = {'id': 1, 'name': 'Alice'} # ✅ using bracket notation print(my_dict['id']) # 👉️ 1 print(my_dict['name']) # 👉️ "Alice" # ✅ using get() method to avoid errors if key not in dict print(my_dict.get('id')) # 👉️ 1 print(my_dict.get('name')) # 👉️ "Alice"
Python uses bracket notation to access a key of a dictionary. However, it should
be noted that if the key is not present in the dict
object, a KeyError
is
thrown.
The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.
The method takes the following 2 parameters:
Name | Description |
---|---|
key | The key for which to return the value |
default | The default value to be returned if the provided key is not present in the dictionary (optional) |
If a value for the default
parameter is not provided, it defaults to None
,
so the get()
method never raises a KeyError
.
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.
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 classes' 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 id
attribute, the error is caused.