字典键和值意外翻转

2024-05-18 08:18:35 发布

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

我运行的是python3.5,我定义了一个函数来创建XML子元素并将它们添加到另一个元素下。属性在字典中,但由于某些原因,在执行脚本时,字典键和值有时会翻转。你知道吗

这是一个我所拥有的代码片段(代码被分解成许多函数,所以我将其组合在这里)

import xml.etree.ElementTree as ElementTree

def AddSubElement(parent, tag, text='', attributes = None):
    XMLelement = ElementTree.SubElement(parent, tag)
    XMLelement.text = text
    if attributes != None:
        for key, value in attributes:
            XMLelement.set(key, value)
    print("attributes =",attributes)
    return XMLelement

descriptionTags = ([('xmlns:g' , 'http://base.google.com/ns/1.0')])
XMLroot = ElementTree.Element('rss')
XMLroot.set('version', '2.0')
XMLchannel = ElementTree.SubElement(XMLroot,'channel')
AddSubElement(XMLchannel,'g:description', 'sporting goods', attributes=descriptionTags )
AddSubElement(XMLchannel,'link', 'http://'+ domain +'/')
XMLitem = AddSubElement(XMLchannel,'item')  
AddSubElement(XMLitem, 'g:brand', Product['ProductManufacturer'], attributes=bindingParam)
AddSubElement(XMLitem, 'g:description', Product['ProductDescriptionShort'], attributes=bindingParam)
AddSubElement(XMLitem, 'g:price', Product['ProductPrice'] + ' USD', attributes=bindingParam)

键和值确实被切换了!因为我有时会在控制台看到:

attributes = [{'xmlns:g', 'http://base.google.com/ns/1.0'}]
attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}]
attributes = [{'http://base.google.com/ns/1.0', 'xmlns:g'}]
...

下面是有时会出现的xml字符串:

<rss version="2.0">
<channel>
    <title>example.com</title>
    <g:description xmlns:g="http://base.google.com/ns/1.0">sporting goods</g:description>
    <link>http://www.example.com/</link>
    <item>
        <g:id http://base.google.com/ns/1.0="xmlns:g">8987983</g:id>
        <title>Some cool product</title>
        <g:brand http://base.google.com/ns/1.0="xmlns:g">Cool</g:brand>
        <g:description http://base.google.com/ns/1.0="xmlns:g">Why is this so cool?</g:description>
        <g:price http://base.google.com/ns/1.0="xmlns:g">69.00 USD</g:price>
        ...

是什么导致了这个翻转?你知道吗


Tags: textcomhttpbasetitlegoogledescriptionattributes