Python Dictionary errors SyntaxError and AttributeError 'dict' object has no attribute 'name'

In this post I want to list two common mistakes made by Python beginners:

  • AttributeError: 'dict' object has no attribute 'name'
  • SyntaxError: invalid syntax

This can occur for creation of new or update/delete of existing value.

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

This mistake can be seen if you try to set map value in wrong way and the dictionary has string as keys. This examples show the error and the right way to set a python dictionary value:

dict = {'name': 'Python', 'val': 'Java', 'key': 'Javascript', 'num':'None'}
dict['name'] = 'Django' # correct 
dict.name = 'Django' # raise error AttributeError: 'dict' object has no attribute 'name'

SyntaxError: invalid syntax

The next mistake is similar to the previous one. The only difference is that we are using as keys integer values. And this will end with different error like:

dict = {1: 'Python', 2: 'Java', 3: 'Javascript', 0:'None'}
dict['1'] = 'Django' # correct
dict.1 = 'Django' # raise error SyntaxError: invalid syntax

Note: If you want to set a default value in python dict you can do it as(to check if the value is not presented already in the map:

dict = {'name': 'Python', 'val': 'Java', 'key': 'Javascript', 'num':'None'
dict.setdefault('version', 0)

this is equivalent to:

if 'version' not in dict:
    dict['version'] = 0

Related Article