AttributeError: 'int' object has no attribute 'get'

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Julie Kwak

AttributeError: 'int' object has no attribute 'get' #

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.

attributeerror int object has no attribute get

Here is an example of how the error occurs.

main.py
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, you need to track down where exactly you are setting the value to an integer in your code and correct the assignment.

To solve the error in the example, we would have to remove the reassignment or correct it.

main.py
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:

NameDescription
keyThe key for which to return the value
defaultThe 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.

main.py
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.