如何在 id 上合并 2 个字典并将它们写入 xml 文件

我有不同对象的产品信息、产品描述和产品亮点。这两个对象都有 product_id,所以我可以将它们关联在一起。


decription_items是字典列表,例如:


[

 {'product_id': '123', 'description': 'desc1', 'price': '$40' },

 {'product_id': '124', 'description': 'desc2', 'price': '$50' },

 {'product_id': '125', 'description': 'desc3', 'price': '$99' },

product_highlight_dictProductHighlight是 (product_id, )的字典


{

 '123': <product_123_highligh>,

 '124': <product_124_highligh>,

 '125': <product_125_highligh>,

}

最后ProductHighlight是一个类:


class ProductHighlight:

    def __init__(self, product_id, location, area):

        self.product_id = product_id

        self.location = location

        self.area = area

我想做的是合并这两种类型并写入一个xml文档,在下面的代码中,我可以合并这两种类型:


for description_item in self.decription_items:

    product_id = .get('product_id')

        if product_id:

            product_highlight = spider.product_highlight_dict.get(product_id)

            # I don't know how to combine description_item and 

            # product_highlight and write them to an xml

更新

我使用以下代码写入product_highlight_dictxml。我不知道如何包含description_item在以下逻辑中?


    highlights = []

    for k in self.product_highlight_dict:

        highlights.append(vars(self.product_highlight_dict[k]))


    xml = dicttoxml.dicttoxml(highlights, custom_root='product_highlights')

    file = open('filename', "wb")

    file.write(xml)

    file.close()


元芳怎么了
浏览 133回答 1
1回答

慕虎7371278

您可以使用每个产品的信息构建description_items字典:descriptionpriceproduct_data = {}for description_item in description_items:&nbsp; &nbsp; product_id = description_item["product_id"]&nbsp; &nbsp; product_data[product_id] = description_item然后你可以像这样在你的代码中使用它highlights = []for product_id, product_highlight in self.product_highlight_dict.items():&nbsp; &nbsp; highlight = vars(product_highlight)&nbsp; &nbsp; if product_id in product_data:&nbsp; &nbsp; &nbsp; &nbsp; highlight.update(product_data[product_id])&nbsp; &nbsp; highlights.append(highlight)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python