排列嵌套的字典项Python

2024-09-27 07:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了这个代码,它是好的,但是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的字段。 提前谢谢。你知道吗


Tags: nameselfcomidchildidsstreetpartner
1条回答
网友
1楼 · 发布于 2024-09-27 07:34:39

你想要一个单一的列表(可能是字典),而不是三个平行的列表。像这样:

aValues['child_ids'] = []


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

相关问题 更多 >

    热门问题