Python递归函数来更改元素值

2024-05-08 22:06:53 发布

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

示例数据=

 OrderedDict([('VaryasyonID', '22369'), ('StokKodu', '01277NUC'), ('Barkod', 'MG100009441'), ('StokAdedi', '1'), ('AlisFiyati', '272,00'), ('SatisFiyati', '272,00'), 
    ('IndirimliFiyat', '126,00'), ('KDVDahil', 'true'), ('KdvOrani', '8'), ('ParaBirimi', 'TL'), 
    ('ParaBirimiKodu', 'TRY'), ('Desi', '1'), 
('EkSecenekOzellik', OrderedDict([('Ozellik', [OrderedDict([('@Tanim', 'Renk'), ('@Deger', 'Ten'), ('#text', 'Ten')]), OrderedDict([('@Tanim', 'Numara'), ('@Deger', '41'), ('#text', '41')])])]))])

如果“#text”在dict中,则它是一个XML值,这意味着其他元组是元素的属性。我必须以这种格式将数据插入数据库

[{'@_value': 'Haki', '@_attributes': {'@Tanim': 'Renk', '@Deger': 'Haki'}}]

我基本上得到了放在“@#u value”键中的#text和“@#u attributes”dict中的其他元组。如果dict不包含“#text”,那么我将其保存为原样

现在,如果我用这个函数来做,它会工作

def get_attrs_to_element(value): ## value type should be dict
        text_value = ''
        res = []
   
        #check for attributes
        for key, val in value.items(): 
            if '#text' in key:
                text_value = value['#text']

                del value['#text']
                attr_obj = {
                    "@_value": text_value,
                    "@_attributes": dict(value)
                }
                res.append(attr_obj)                
                return res
                
        return value

我调用这个函数,迭代整个XML,因为它们是键值元组

           if isinstance(value, dict):
                whole_dict[key] = get_attrs_to_element(value)

现在这是可行的。但我也需要这个函数在有类似于上述数据的嵌套元素时工作。dict中还有另一个dict,我需要检查其中是否有“#text”属性。所以我尝试递归

我喜欢这样做

def get_attrs_to_element(value): ## value type should be dict
        text_value = ''
        res = []
    

        # if it only contains xmlns and text: take text only
        obj_list = list(value.keys())
        if len(obj_list) == 2 and '@xmlns' in obj_list and '#text' in obj_list:
            return value['#text']  # CHECK IF IT IS #text IN ALL XMLs

        #check for attributes
        for key, val in value.items(): 
            if '#text' in key:
                text_value = value['#text']

                del value['#text']
                attr_obj = {
                    "@_value": text_value,
                    "@_attributes": dict(value)
                }
                res.append(attr_obj)                
                return res
                

            if isinstance(val, dict):
                val = get_attrs_to_element(val)

            if type(val) is list:
                for disk in val:
                    if isinstance(disk, dict):
                        disk = get_attrs_to_element(disk)
        return value

因此,如果存在dict或dict列表,我将调用该函数,并将其值更改为返回值(res)。然而,我不能让它像我想要的那样工作。结果出人意料地相似

OrderedDict([('Ozellik', [OrderedDict([('@Tanim', 'Renk'), ('@Deger', 'Mavi')]), OrderedDict([('@Tanim', 'Numara'), ('@Deger', '38')])])

(只删除嵌套元素中的#文本,但不正确添加attr#u obj)

我做错了什么,好几个小时都看不见。请帮忙


热门问题