安排嵌套的dict项Python

时间:2017-05-16 12:25:36

标签: python defaultdict

我已经编写了这段代码并且很好,但是dict的输出并不是我想要的。这是代码:

class EbExportCustomer(models.Model):
    _inherit = 'res.partner'

    @api.one
    def get_pa_data(self):
        aValues = defaultdict(dict)
        aValues['partner_id'] = self.id
        aValues['name'] = self.name
        aValues['street'] = self.street
        aValues['street2'] = self.street2
        aValues['zip'] = self.zip
        aValues['city'] = self.city
        aValues['country'] = self.country_id.name
        aValues['state'] = self.state_id.name
        aValues['email'] = self.email
        aValues['website'] = self.website
        aValues['phone'] = self.phone
        aValues['mobile'] = self.mobile
        aValues['fax'] = self.fax
        aValues['language'] = self.lang
        aValues['child_ids']['name'] = []
        aValues['child_ids']['function'] = []
        aValues['child_ids']['email'] = []


        if self.child_ids:
            for child in self.child_ids:
                aValues['child_ids']['name'].append(child.name)
                aValues['child_ids']['function'].append(child.function)
                aValues['child_ids']['email'].append(child.email)

        return aValues

我目前正在使用dicttoxmlcollections.defaultdict,输出为:

 <Partner><item>
 <website>http://www.chinaexport.com/</website>
 <city>Shanghai</city>
 <fax>False</fax>
 <name>China Export</name>
 <zip>200000</zip>
 <mobile>False</mobile>
 <country>China</country>
 <street2>False</street2>
 <child_ids>
  <function>
   <item>Marketing Manager</item>
   <item>Senior Consultant</item>
   <item>Order Clerk</item>
   <item>Director</item>
  </function>
 <name>
  <item>Chao Wang</item>
  <item>David Simpson</item>
  <item>Jacob Taylor</item>
  <item>John M. Brown</item>
 </name>
<email><item>chao.wang@chinaexport.example.com</item>      \ <item>david.simpson@epic.example.com</item><item>jacob.taylor@millennium.example.com</item><item>john.brown@epic.example.com</item></email></child_ids><phone>+86 21 6484 5671</phone><state>False</state><street>52 Chop Suey street</street><language>en_US</language><partner_id>9</partner_id><email>chinaexport@yourcompany.example.com</email>

但我需要child_ids的输出如下:

<child_id>
< function > 
 Marketing
Manager 
</function>
< name >Chao
Wang  </ name >
< email >  chao.wang @ chinaexport.example.com </ email>
</child id>

然后另一个<child id>包含来自所有其他子ID的字段。 提前谢谢。

1 个答案:

答案 0 :(得分:4)

您需要单个列表(可能是字典),而不是三个并行列表。像这样:

aValues['child_ids'] = []


for child in self.child_ids:
    aValues['child_ids'].append({
        'name': child.name,
        'function': child.function,
        'email': child.email
    })