AttributeError: ‘dict’ object has no attribute ‘key’ in python
When trying to access a Python object property like below, I get the ttributeError: 'dict' object has no attribute 'key' in python error.
myObject = {'key': 'value'}
print(myObject.key)
Why is This Error?
The error “AttributeError: ‘dict’ object has no attribute ‘key’” in Python occurs when you try to access an attribute called ‘key’ on a dictionary using dot notation. However, dictionaries in Python don’t have attributes accessed this way; instead, you should use square bracket notation to access values using keys.
Here’s the corrected version of your code
myObject = {'key': 'value'}
print(myObject['key'])
In this corrected code
- The dictionary
myObject
is defined with the key-value pair'key': 'value'
. - To access the value associated with the key ‘key’, you use square bracket notation (
myObject['key']
), which returns the value'value'
. - Printing
myObject['key']
will output'value'
.
In Python, dictionaries are collections of key-value pairs, and you access values by specifying the key within square brackets. The dot notation is used for accessing attributes of objects, but dictionaries are not objects with attributes in the same way as some other types in Python.
Comments
-
Danielle Carline
Posted on
Python doesn’t support dot notation to access properties in a Python object. But you can access object properties by the get method.
myObject = {'key': 'value'} print(myObject.get('key'))
Or else you can use the following notation to access object properties.
myObject = {'key': 'value'} print(myObject['key'])