【发布时间】:2015-02-16 08:38:24
【问题描述】:
我遇到了一种情况,我试图在 Python 中使用字典来跟踪 ID 和 CLASSNAME。我正在使用字典,因为我需要知道 CLASSNAME 属于哪个 ID。但是,虽然我只有一个 ID,但我可以有多个 CLASSNAME(S)。这是我在代码中所做的 sn-p。由于我将 key:value 添加到字典的方式,我只获得了该键的最后一个值,而不是所有值。
elementTree = self.param2
audio = {}
if elementTree.find('./connections') is None:
return
else:
for connection_element in elementTree.findall('.//connections/connection'):
# Get the type for this connection.
controlType = connection_element.find('type')
# Get the id for this connection.
connectionID = connection_element.find('id')
if controlType is not None and str(controlType.text) == '6':
# Now find all of the classname(s) in this specific connection element.
for class_name in connection_element.findall('classes/class/classname'):
audio[connectionID.text] = class_name.text
return audio
以下是上述函数试图解析的数据示例:
<connection>
<id>3002</id>
<type>6</type>
<classes>
<class>
<classname>DIGITAL_COAX</classname>
</class>
<class>
<classname>DIGITAL_OPTICAL</classname>
</class>
<class>
<classname>STEREO</classname>
</class>
</classes>
</connection>
我目前得到的是 3002:STEREO。 3002 是 ID,STEREO 是 CLASSNAME。我想要返回的是如下内容:
3002:DIGITAL_COAX
3002:DIGITAL_OPTICAL
3002:STEREO
如何正确使用字典来确保可以为同一个键分配多个值?
【问题讨论】:
-
字典中每个键只能有一个值;但是,请注意,一个值可能是某种容器(例如,另一个字典或列表)。
标签: python python-2.7 dictionary elementtree