The Agri CULTURE Guy
The Agri CULTURE Guy

Reputation: 69

Arrange nested dict items Python

I have written this code and it is fine, but the output of the dict is not what i want. Here is the code:

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

I am currently using dicttoxml and collections.defaultdict, The output is this:

 <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>[email protected]</item>      \ <item>[email protected]</item><item>[email protected]</item><item>[email protected]</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>[email protected]</email>

But i would need the output for child_ids to be like:

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

And then another <child id> with the fields from all the other child ids. Thanks in advance.

Upvotes: 1

Views: 129

Answers (1)

jasonharper
jasonharper

Reputation: 9597

You want a single list (of dictionaries, probably), rather than three parallel lists. Something like this:

aValues['child_ids'] = []


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

Upvotes: 4

Related Questions