Dict’ Object Has No Attribute ‘Key’ in Python 3

The Python error we are discussing here is of AttributeError class. AttributeError generally occurs because an attribute (function object of a class) you are trying to access does not exist.

The general solution is to always ensure that the attribute/method you are trying to access exists. This also includes checking how you spell it – small and capital letters matters because Python is a case-sensitive language.

A Quick Answer

Python dictionary supports the following methods ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘items’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, and  ‘values’. Any attempt to use an attribute not supported by the object leads to AttributeError.

dict1 = {'Name': 'Smith', "Adm": 45}
dict1.Key("name")

Output:

AttributeError: 'dict' object has no attribute 'Key'

If you want to get all the keys in the dictionary, use keys(), if you want to access the value of a given key use <dict>.get(<key>) or <dict>[<key>], that is,

dict1 = {'Name': 'Smith', "Adm": 45}
print(dict1.keys())
print(dict1["Name"])
print(dict1.get("Adm"))

Output:

dict_keys(['Name', 'Adm'])
Smith
45

The rest of the article covers other reasons that cause AttributeError and also goes into detail on AttributeError when working with Python dictionaries.

Reproducing AttributeError

The following code snippet defines a class named ExampleClass that supports one function –add_func(). The code shows how AttributeError can be reproduced.

class ExampleClass():
    def add_func(self, a):
   	 return a*2
s = ExampleClass()
s.Add_func(6)

Output:

AttributeError: 'ExampleClass' object has no attribute 'Add_func'

Python throws AttributeError because ExampleClass does not support the function ‘Add_func’. This is just a case of misspelled function name.

Python data types like strings, lists, sets, and dictionaries also have specific functions related to them. For example, as shown below, the list object supports the append function, but the string does not. Therefore, any attempt to use the append function for string data type leads to AttributeError.

list1 = [34, 56, "City"]
list1.append(89)
print(list1)

Output:

[34, 56, 'City', 89]
name = "Smit"
name.append("h")
print(name)

Output:

AttributeError: 'str' object has no attribute 'append'

[Note]: When calling functions on Python modules and packages, ensure they exist; otherwise, Python will also throw AttributeError. Example,

import numpy as np
aa = np.arr([1, 4, 5])

Output:

AttributeError: module 'numpy' has no attribute 'arr'

Reproducing and Solving Dict’ Object Has No Attribute ‘Key’ Error

Like in lists and strings shown in the previous example, the Python dictionary also supports specific methods, and any attempt to access an unsupported method results in AttributeError. For example,

dict1 = {"Name": "Smith", "Reg": 445}
dict1.Key("Name")

Output:

AttributeError: 'dict' object has no attribute 'Key'

Python dictionary does not support the attribute “Key” hence the error. You can use the function dir(<object>) to check functions supported by a given object.

dir(dict1)

Output:

['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

Any Python dictionary supports the methods shown in the above list. More often than not, we only use the functions without underscores around them.

The functions with two underscores at the prefix and suffix are called magic/functions. These are specials mostly called by Python in the background to accomplish some tasks. For example, when we ask Python to compute 4+7, Python performs the calculation using __add__ dunder function as 4.__add__(7).

Below are some used cases of the functions displayed in the above list.

  • The attribute get() is used to get the value given a key. It returns the value if the key exists; otherwise, it returns None. This function is a better alternative than using [ ] because the latter returns an error if the key does not exist.
dict1 = {"Name": "Smith", "Reg": 445}
print(dict1.get("Name"))
print(dict1.get("name"))
print(dict1["Reg"])
print(dict1["Adm"])

Output:

Smith
None
445
KeyError: 'Adm'

The method keys() is used to extract a dictionary’s keys, whereas values() is used to get the values. items() get them both in tuples.

dict1 = {"Name": "Smith", "Reg": 445}
print(dict1.keys())
print(dict1.values())
print(dict1.items())

Output:

dict_keys(['Name', 'Reg'])
dict_values(['Smith', 445])
dict_items([('Name', 'Smith'), ('Reg', 445)])

You can cast the results into Python lists using the list (< object>) function.

If you are running Python3 instead of Python2, you might run into a ‘dict’ object that has no attribute ‘has_key’.

Reproducing and solving the ‘dict’ object has no attribute ‘has_key’

Python3 does not support the has_key() method, but Python2 does. Therefore, if you use has_key() in Python3, you will run into a ‘dict’ object that has no attribute ‘has_key’ error.

dict1 = {"Name": "Smith", "Reg": 445}
print(dict1.has_key("Name"))

Output (running Python2):

True

Output (executing on Python3):

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

Solution

If you are running Python2, you can use has_key() to check if a key exists or not, but if you are running Python3, you can use the magic method __contains__(<key>) or get(<key>) method.

The former returns True if the key exists, else False, whereas the latter returns the value if the key exists or None if not (get(<key>) examples are shown in the previous section). Python2 also supports using the __contains__(<key>) method. Example:

dict1 = {"Name": "Smith", "Reg": 445}
print(dict1.__contains__("Name"))
print(dict1.__contains__("name"))

Output:

True
False

Conclusion

This article covered the causes and how to solve AttributeError in Python. To avoid the error, always make sure that you call the existing methods of modules/objects/classes. You may need to check the spelling of the attribute. Methods available for a given object can be listed using dir().