首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在id上合并2个字典并将它们写入到一个xml文件中

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

Stack Overflow用户
提问于 2020-07-14 16:17:35
回答 1查看 25关注 0票数 0

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

decription_items是一个字典列表,例如:

代码语言:javascript
复制
[
 {'product_id': '123', 'description': 'desc1', 'price': '$40' },
 {'product_id': '124', 'description': 'desc2', 'price': '$50' },
 {'product_id': '125', 'description': 'desc3', 'price': '$99' },
] 

product_highlight_dict是(product_id,ProductHighlight)的字典

代码语言:javascript
复制
{
 '123': <product_123_highligh>,
 '124': <product_124_highligh>,
 '125': <product_125_highligh>,
}

最后,ProductHighlight是一个类:

代码语言:javascript
复制
class ProductHighlight:
    def __init__(self, product_id, location, area):
        self.product_id = product_id
        self.location = location
        self.area = area

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

代码语言:javascript
复制
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_dict写成xml。我不知道如何在下面的逻辑中包含description_item

代码语言:javascript
复制
    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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-14 17:43:01

您可以使用description_items为每个产品构建一个包含descriptionprice信息的字典:

代码语言:javascript
复制
product_data = {}
for description_item in description_items:
    product_id = description_item["product_id"]
    product_data[product_id] = description_item

然后,您可以在代码中使用它,如下所示

代码语言:javascript
复制
highlights = []
for product_id, product_highlight in self.product_highlight_dict.items():
    highlight = vars(product_highlight)
    if product_id in product_data:
        highlight.update(product_data[product_id])
    highlights.append(highlight)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62890851

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档