Last updated: Apr 8, 2024
Reading time·8 min
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']
.
Here is an example of how the error occurs.
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.
my_dict = {'name': 'Bobby Hadz', 'age': 30} # ✅ Using bracket notation print(my_dict['name']) # 👉️ "Bobby Hadz" print(my_dict['age']) # 👉️ 30
You can also use the get()
method to avoid getting an error if the key is not
present in the dictionary.
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'
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
.
dict
class.If you are trying to add key-value pairs to a dictionary, use bracket notation.
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.
If you need to iterate over a dictionary, use the items()
method.
my_dict = {'name': 'Bobby Hadz', 'age': 30} for key, value in my_dict.items(): # name Bobby Hadz # age 30 print(key, value)
If you need to
check if a key exists in a dictionary,
use the in
operator.
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.
Make sure you aren't reassigning the value of your variable somewhere in your code.
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.
If you meant to use a class instead of a dictionary, instantiate the class before accessing attributes.
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.
If you need to check whether an object contains an attribute, use the hasattr
function.
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:
Name | Description |
---|---|
object | The object we want to test for the existence of the attribute |
name | The 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.
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 will get the error.
Here are 3 examples of solving the error for specific methods. Click on the link to navigate to the subheading.
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.
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')
has_key
method was removed in Python 3The 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.
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
.
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.
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.
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']
.
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.
Here is an example of how the error occurs.
my_dict = {'name': 'Alice', 'age': 30} # ⛔️ AttributeError: 'dict' object has no attribute 'append' my_dict.append('country', 'Austria')
Dictionaries don't have an append
method. Use bracket notation to add a
key-value pair to a dictionary.
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
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.
When declaring a list, use square brackets instead of curly braces.
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
.
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.
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 will get the error.
Since dict
objects don't have an append()
method, the error is caused.
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.
Here is an example of how the error occurs.
import json my_dict = {"name": "Alice", "age": 30} # ⛔️ AttributeError: 'dict' object has no attribute 'read' json_str = json.load(my_dict)
If you are trying to convert a Python object to a JSON string, use the
json.dumps()
method.
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.
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.
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.
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.
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.
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 will get the error.
Since dict
objects don't have a read()
method, the error is caused.