【问题标题】:How to add multiple values to the same key in a Python Dictionary如何将多个值添加到 Python 字典中的同一个键
【发布时间】: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


【解决方案1】:

使用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))

【讨论】:

  • 好的,这似乎有效。我现在每个键都有多个值。但是现在如何迭代呢?以前当它是一本字典时,我会使用类似的东西:for id, classname in myDictionary.interitems(): print id, classname。使用 defaultdict 会有什么变化?
  • 只遍历字典本身,然后对于 d[k]:print k,val 中的 val,我添加了一个示例
  • 效果很好!谢谢。
  • 谢谢你,我一直想弄清楚为什么我不能使用具有不同值的多个相同键,现在我知道了。
猜你喜欢
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 2023-03-31
  • 2021-04-30
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多