Last modified: Dec 09, 2025 By Alexander Williams

Fix AttributeError: 'dict' object has no attribute 'keys'

Python errors can be confusing. The AttributeError is a common one.

It often means you tried to use a method on the wrong type of object.

This guide explains the 'dict' object has no attribute 'keys' error.

We will show you why it happens and how to fix it step by step.

Understanding the AttributeError

An AttributeError occurs in Python.

It happens when you try to access an attribute or method.

The object you are using does not have that attribute or method.

For example, the keys() method belongs to dictionary objects.

If you call keys() on a list, you will get an AttributeError.

The error message will tell you which object type is the problem.

It also tells you which attribute it tried and failed to find.

Why 'dict' object has no attribute 'keys'?

This error seems contradictory. Dictionaries do have a keys() method.

The key insight is the word 'dict' in the error message.

It refers to the built-in dict class, not your variable.

This usually means you have overwritten the dict name.

You have likely used dict as a variable name in your code.

By doing this, you shadow the original dictionary class.

Your variable named dict is not a dictionary instance.

It is probably a different data type, like a string or integer.

When you call .keys() on it, Python rightly says it has no such method.

Common Cause: Variable Shadowing

The most common cause is variable shadowing.

You assign a value to a variable named dict.

This overwrites the reference to the dictionary class.

Later, you try to use dict.keys() or my_dict.keys().

But dict is no longer the class you think it is.

Look at this example that causes the error.


# Example causing the error
dict = {"name": "Alice", "age": 30}  # This shadows the built-in dict
print(dict.keys())  # AttributeError!

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'dict' object has no attribute 'keys'

Here, dict is a variable holding a dictionary.

But the name dict itself is now bound to that instance.

The built-in class is hidden. The error message is misleading.

It says 'dict' object, meaning your variable, not the class.

How to Diagnose and Fix the Error

Follow these steps to find and solve the problem.

Step 1: Check for Variable Named 'dict'

Search your code for any line that uses dict = ....

This is the most likely culprit. Never use built-in names as variables.

Names like list, str, int, or file are also risky.

If you find it, rename the variable to something descriptive.

For example, use user_data or config_dict instead.


# The Fix: Rename the variable
user_data = {"name": "Alice", "age": 30}  # Good variable name
print(user_data.keys())  # This works perfectly

dict_keys(['name', 'age'])

Step 2: Verify the Object Type

If you didn't shadow dict, your object might not be a dictionary.

Use the type() function to check the object's type.

Or use isinstance() to see if it's a dict.

This helps confirm what you are actually working with.

Similar issues can occur with lists, like the AttributeError: 'list' object has no attribute 'split'.


my_var = [1, 2, 3]  # This is a list, not a dict
print(type(my_var)) # Check the type
# print(my_var.keys()) # This would cause an error

<class 'list'>

Step 3: Check Function Returns

Sometimes a function returns a non-dictionary.

You might expect a dict but get a list, string, or None.

Always check the documentation for the functions you call.

Print the return value to see its type and structure.

Errors like AttributeError: 'NoneType' Object Has No Attribute 'append' follow the same logic.

Step 4: Restart Your Python Session

If you are in an interactive shell (like IDLE or Jupyter), you may have shadowed dict earlier.

The shadowing persists in that session. Restarting the kernel or interpreter clears it.

This restores dict to its original meaning as a class.

Best Practices to Avoid This Error

Follow these tips to prevent this and similar errors.

Avoid built-in names. Never use dict, list, str, etc., as variable names.

Use descriptive names. Name variables after their content or purpose.

Validate data types. Check types when receiving data from external sources.

Read error messages carefully. The error tells you the object type. Trust it.

These practices also help avoid errors in frameworks like Django, such as the AttributeError: module 'django.db.models' has no attribute 'model'.

Example: A Real-World Scenario

Imagine you are processing API data. The API might return different formats.

Your code expects a dictionary but sometimes gets a list.

Handling this gracefully prevents crashes.


import json

api_response = '["apple", "banana", "cherry"]'  # This is a JSON list, not a dict
try:
    data = json.loads(api_response)
    if isinstance(data, dict):
        keys = data.keys()
        print("Keys:", keys)
    else:
        print(f"Expected a dict, but got a {type(data).__name__}. Data: {data}")
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)

Expected a dict, but got a list. Data: ['apple', 'banana', 'cherry']

This code safely handles the case. It does not assume the type.

It checks with isinstance() before calling dictionary methods.

This is a robust programming pattern.

Similar defensive checks are useful for libraries like googletrans to avoid the AttributeError: 'NoneType' object has no attribute 'group'.

Conclusion

The AttributeError 'dict' object has no attribute 'keys' is usually a naming issue.

You have likely used dict as a variable name.

This shadows the built-in dictionary class.

The fix is simple: rename your variable.

Always avoid Python's built-in names for your variables.

Use descriptive names and validate object types in your code.

Understanding this error helps you debug similar AttributeErrors in Python.

It makes you a more careful and effective programmer.