'dict' object has no attribute 'id'

Question:

This is my code. I’m trying to translate xml string into python list to be shown in html template.

self.task_xml = "<?xml version="1.0" encoding="utf-8"?>
    <django-objects version="1.0">
<object model="task.task" pk="31">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">0</field>
</object>
<object model="task.task" pk="32">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">0</field>
</object>
<object model="task.task" pk="33">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">31</field>
</object>
<object model="task.task" pk="34">
<field name="name" type="CharField">New Task</field>
<field name="parent_task_id" type="IntegerField">31</field>
</object>
</django-objects>"

 58         self.xmlData = ET.fromstring(self.db.task_xml)
 59 
 60         self.task_list = []
 61         taskList = []                                                           
 62         for obj in self.xmlData.iter("object"):
 63             parent_task_id = obj.find("field[@name='parent_task_id']").text
 64             if parent_task_id == EMPTY_UUID:
 65                 taskList.append({'id': obj.get("pk"),
 66                     'name': obj.find("field[@name='name']").text,
 67                     'parent_task_id': parent_task_id ,
 68                     })
 69         # Apprend taskList:
 70         for task in taskList:
 71             taskViewModel = TaskViewModel(task.id, True)
 72             self.task_list.append(taskViewModel)

But I’m getting the error:

'dict' object has no attribute 'id'

And it is task.id in line 71

Do you think I have a problem with this in line 65:

'id': obj.get("pk")
Asked By: James Reid

||

Answers:

You are accessing the dictionary wrongly. You need to use subscript with string 'id' , Example –

taskViewModel = TaskViewModel(task['id'], True)
Answered By: Anand S Kumar

I got the same error when accessing "id" in dictionary with dot "." like JavaScript as shown below because I also use JavaScript quite often in addition to Python:

user = {"id": 1, "name": "John"}
print(user.id) # Error

So, I accessed "id" with brackets "[]" as shown below then the error was solved:

user = {"id": 1, "name": "John"}
print(user["id"]) # 1
Answered By: Kai – Kazuya Ito
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.