如何在Python字典中向同一个键添加多个值

时间:2014-12-17 17:44:41

标签: python python-2.7 dictionary elementtree

我有一种情况,我试图在Python中使用字典来跟踪ID和CLASSNAME。我正在使用字典,因为我需要知道CLASSNAME属于哪个ID。但是,虽然我只有一个ID,但我可以拥有多个CLASSNAME(S)。这是我在代码中所做的事情的片段。由于我将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

如何正确使用词典以确保我可以为同一个键分配多个值?

1 个答案:

答案 0 :(得分:4)

使用defaultdict将值附加到列表中:

from collections  import defaultdict

audio = defaultdict(list)

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].append(class_name.text)
    return audio

使用audio[connectionID.text] = class_name.text将在每次循环时覆盖该值,dicts不能有重复键,因此使用列表可以追加并存储每个键的所有值。

如果要打印键和值:

for k in audio:
    for val in audio[k]:
        print("{}:{}".format(k,val))

或者:

for k,vals in audio.iteritems():
    for val in vals:
        print("{}:{}".format(k,val))