AttributeError: 'dict' object has no attribute 'X' in Python

avatar
Borislav Hadzhiev

Last updated: Jan 29, 2023
8 min

banner

# Table of Contents

  1. AttributeError: 'dict' object has no attribute X
  2. AttributeError: 'dict' object has no attribute 'has_key'
  3. AttributeError: 'dict' object has no attribute 'append'
  4. AttributeError: 'dict' object has no attribute 'read'

# 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'].

attributeerror dict object has no attribute

Here is an example of how the error occurs.

main.py
my_dict = {'id': 1, 'name': 'Bobby Hadz', 'age': 30} # ⛔️ AttributeError: 'dict' object has no attribute 'name' print(my_dict.name) # ⛔️ AttributeError: 'dict' object has no attribute 'id' print(my_dict.id)

If you are trying to access a key in a dictionary, use bracket notation.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} # ✅ using bracket notation print(my_dict['name']) # 👉️ "Bobby Hadz" print(my_dict['age']) # 👉️ 30

access dictionary key

You can also use the get() method to avoid getting an error if the key is not present in the dictionary.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} print(my_dict.get('name')) # 👉️ "Bobby Hadz" print(my_dict.get('age')) # 👉️ 30 print(my_dict.get('another')) # 👉️ None print(my_dict.get('antoher', 'default')) # 👉️ 'default'

access dictionary key using get

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.

The error means that we are trying to access an attribute or call a method on a dictionary that is not implemented by the dict class.

# Adding a key-value pair to a dictionary

If you are trying to add key-value pairs to a dictionary, use bracket notation.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} my_dict['country'] = 'Austria' my_dict['job'] = 'programmer' # 👇️ {'name': 'Bobby Hadz', 'age': 30, 'country': 'Austria', 'job': 'programmer'} print(my_dict)

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.

# Iterating over the key-value pairs of a dictionary

If you need to iterate over a dictionary, use the items() method.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} for key, value in my_dict.items(): # name Bobby Hadz # age 30 print(key, value)
Make sure you aren't misspelling a built-in method's name because method names are case-sensitive.

# Checking if a key exists in a dictionary

If you need to check if a key exists in a dictionary, use the in operator.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} print('name' in my_dict) # 👉️ True print('age' in my_dict) # 👉️ True print('another' in my_dict) # 👉️ False if 'age' in my_dict: print(my_dict['age']) # 👉️ 30 else: print('The age key does NOT exist')

The in operator returns True if the key exists in the dictionary and False otherwise.

# Reassigning a variable to a dictionary by mistake

Make sure you aren't reassigning the value of your variable somewhere in your code.

main.py
my_list = ['a', 'b'] # 👇️ reassign the list to a dictionary by mistake my_list = {'name': 'Bobby Hadz'} # ⛔️ AttributeError: 'dict' object has no attribute my_list.append('c')

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.

# Using a class instead of a dictionary

If you meant to use a class instead of a dictionary, instantiate the class before accessing attributes.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name emp1 = Employee('bobbyhadz', 100) print(emp1.name) # 👉️ bobbyhadz print(emp1.salary) # 👉️ 100 print(emp1.get_name()) # 👉️ bobbyhadz

We supplied the name and salary arguments and instantiated the Employee class.

You can access attributes on the emp1 instance using dot notation.

# Check if an object contains an attribute before accessing the attribute

If you need to check whether an object contains an attribute, use the hasattr function.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} if hasattr(my_dict, 'values'): print(my_dict.values()) # 👉️ dict_values(['Bobby Hadz', 30]) else: print('Attribute not present in object')

The hasattr function takes the following 2 parameters:

NameDescription
objectThe object we want to test for the existence of the attribute
nameThe 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.

main.py
my_dict = {'name': 'Bobby Hadz', '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 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 error.

# Examples of solving the error for specific methods

Here are 3 examples of solving the error for specific methods. Click on the link to navigate to the subheading.

  1. AttributeError: 'dict' object has no attribute 'has_key'
  2. AttributeError: 'dict' object has no attribute 'append'
  3. AttributeError: 'dict' object has no attribute 'read'

# AttributeError: 'dict' object has no attribute 'has_key'

If you got the "AttributeError: 'dict' object has no attribute 'has_key'" error, use the in operator to check if a key exists in a dictionary.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} # ⛔️ AttributeError: 'dict' object has no attribute 'has_key' if my_dict.has_key('age'): print('Key in dict')

attributeerror dict object has no attribute has key

# The has_key method was removed in Python 3

The has_key method has been removed in Python 3, however, we can use the in operator to check if a key is in a dictionary.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} # ✅ Check if a key is in a dictionary if 'age' in my_dict: print('age key is in dictionary') print(my_dict['age']) # 👉️ 30 # ✅ Check if a key is NOT in a dictionary if 'some_key' not in my_dict: print('key is NOT in dictionary')

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

x not in s returns the negation of x in s.

When used with a dictionary, the in operators check for the existence of the specified key in the dict object.

You can use the get() method to access a key in a dictionary without getting a KeyError if the key is not present.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 30} print(my_dict.get('name')) # 👉️ "Bobyb Hadz" print(my_dict.get('another')) # 👉️ None print(my_dict.get('another', 'default val')) # 👉️ default val

The dict.get() method takes an optional second argument that serves as a default value if the key doesn't exist in the dictionary.

# Conclusion

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'].

  1. AttributeError: 'dict' object has no attribute 'append'
  2. AttributeError: 'dict' object has no attribute 'read'

# AttributeError: 'dict' object has no attribute 'append'

The Python "AttributeError: 'dict' object has no attribute 'append'" occurs when we try to call the append() method on a dictionary.

To solve the error, use bracket notation to add a key-value pair to a dict or make sure to call the append() method on a list.

attributeerror dict object has no attribute append

Here is an example of how the error occurs.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ⛔️ AttributeError: 'dict' object has no attribute 'append' my_dict.append('country', 'Austria')

# Use bracket notation to add a key to a dictionary

Dictionaries don't have an append method. Use bracket notation to add a key-value pair to a dictionary.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ✅ add key-value pairs to dict my_dict['country'] = 'Austria' my_dict['prof'] = 'programmer' # {'name': 'Alice', 'age': 30, 'country': 'Austria', 'prof': 'programmer'} print(my_dict) print(my_dict['country']) # 👉️ Austria
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 are trying to add an item to a list, you have to figure out where the variable got assigned a dictionary instead of a list.

# Use square brackets when declaring a list

When declaring a list, use square brackets instead of curly braces.

main.py
my_list = [] my_list.append('a') my_list.append('b') print(my_list) # 👉️ ['a', 'b']

Make sure you aren't reassigning a list to a dictionary somewhere in your code before you call append.

main.py
my_list = [] # 👇️ reassign to dictionary by mistake my_list = {'name': 'Alice'} # ⛔️ AttributeError: 'dict' object has no attribute 'append' print(my_list.append('hi'))

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.

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

Since dict objects don't have an append() method, the error is caused.

# AttributeError: 'dict' object has no attribute 'read'

The "AttributeError: 'dict' object has no attribute 'read'" occurs when we try to access the read attribute on a dictionary, e.g. by passing a dict to json.load().

To solve the error, use the json.dumps() method if trying to convert a dictionary to JSON.

attributeerror dict object has no attribute read

Here is an example of how the error occurs.

main.py
import json my_dict = {"name": "Alice", "age": 30} # ⛔️ AttributeError: 'dict' object has no attribute 'read' json_str = json.load(my_dict)

# Converting a Python object to a JSON string

If you are trying to convert a Python object to a JSON string, use the json.dumps() method.

main.py
import json my_dict = {"name": "Alice", "age": 30} json_str = json.dumps(my_dict) print(json_str) # 👉️ '{"name": "Alice", "age": 30}'' print(type(json_str)) # 👉️ <class 'str'>

The json.dumps method converts a Python object to a JSON formatted string.

The json.loads method parses a JSON string into a native Python object.

main.py
import json json_str = r'{"name": "Alice", "age": 30}' my_dict = json.loads(json_str) print(type(my_dict)) # 👉️ <class 'dict'>

If the data being parsed is not a valid JSON string, a JSONDecodeError is raised.

# Deserializing a file using json.load()

If you are trying to use the json.load() method to deserialize a file to a Python object, open the file and pass the file object to the json.load() method.

main.py
import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_data = json.load(f) print(my_data) # 👉️ {'name': 'Alice', 'age': 30}

The json.load method is used to deserialize a file to a Python object, whereas the json.loads method is used to deserialize a JSON string to a Python object.

The json.load() method expects a text file or a binary file containing a JSON document that implements a .read() method. If you call the json.load() method with a dictionary, it tries to call the read() method on the dictionary.

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.

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

Since dict objects don't have a read() method, the error is caused.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.