Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Julie Kwak
The Python "AttributeError: 'int' object has no attribute 'get'" occurs when
we call the get()
method on an integer. To solve the error, make sure the
value you are calling get()
on is of type dict
.
Here is an example of how the error occurs.
employee = {'name': 'Alice', 'age': 30} employee = 100 print(type(employee)) # 👉️ <class 'int'> # ⛔️ AttributeError: 'int' object has no attribute 'get' print(employee.get('name'))
We reassigned the employee
variable to an integer and tried to call the
get()
method on the integer which caused the error.
If you print()
the value you are calling get()
on, it will be an integer.
To solve the error in the example, we would have to remove the reassignment or correct it.
employee = {'name': 'Alice', 'age': 30} print(employee.get('name')) # 👉️ 'Alice'
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
.
You might also be assigning the result of calling a function that returns an integer to a variable.
def get_employee(): return 100 employee = get_employee() # ⛔️ AttributeError: 'int' object has no attribute 'get' print(employee.get('name'))
The employee
variable gets assigned to the result of calling the
get_employee
function.
The function returns an integer, so we aren't able to call get()
on it.
To solve the error, you have to track down where the specific variable gets assigned an integer instead of a dict and correct the assignment.