【问题标题】:Append new values to the similar keys python dictionary将新值附加到类似的键 python 字典
【发布时间】:2017-11-27 17:02:18
【问题描述】:

我有一棵树,我正在使用映射方法遍历树(即具有相似键的节点必须聚集在一起)假设根节点标记为 0,根节点的左侧为 -1,根节点的右侧为 +1。遍历整棵树,将每个节点的HD(与根的水平距离)赋值为节点的key,将节点的数据赋值为value。现在我想在字典中的一个位置附加所有具有相似键的值,例如 {0: ['10','13'], 1: ['12'], -2: ['12'], -1: ['11']} 用于下面创建的树。

代码

class node:
    dict1={}
    def __init__(self,data):
        self.data=data
        self.left=None
        self.right=None

    def check_if_exists(self,hd,root):
      if not self.dict1:
          self.dict1[hd] = [root.data]
      else:
            if hd in self.dict1.keys():  ###Checking if key already exists for some node
                self.dict1[hd].append(root.data)
            else:
                self.dict1[hd] = [root.data]

    def vertical_order_tree(self,root,hd):
        if root:
                self.check_if_exists(hd,root)
                self.vertical_order_tree(root.left,hd-1)
                self.vertical_order_tree(root.right,hd+1)


root=node("10")
root.left=node("11")
root.left.left=node("12")
root.right=node("12")
#root.right.left=node("13")
root.vertical_order_tree(root,0)
print(root.dict1)

输出:

self.dict1[hd].append(root.data)
AttributeError: 'str' object has no attribute 'append'

附加相似的值会导致问题。任何人都可以在这里捕获错误。我不擅长处理字典。

【问题讨论】:

  • 错误提示self.dict1[hd]是一个字符串,而你认为​​它是一个列表。您不能附加到字符串。
  • 是的,我知道,但是在哪里以及改变什么对我来说是个问题。所以一个正确的代码可以在这里帮助我
  • if not self.dict1: 中的self.dict1[hd] = root.data 替换为self.dict1[hd] = [root.data]。您错误地在字典中插入了字符串而不是列表。
  • {0: ['13'], 1: ['12'], -2: ['12'], -1: ['11']} 被替换后@VasilisG。 10 被 13 覆盖
  • 我忘记提及的另一个更改是:删除 for k,v in self.dict1.items(): if k==hd: 并简单地输入 if hd in self.dict1.keys():。请参阅问题中的编辑。

标签: python dictionary data-structures tree


【解决方案1】:

错误says self.dict[hd] 是一个字符串。尝试使用self.dict[hd]+=root.data 而不是self.dict[hd].append(root.data)。当然,前提是root.data 是另一个字符串。

如果您希望该键的值是一个列表,那么我建议首先在该键处创建一个空列表,然后附加

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2021-12-24
    相关资源
    最近更新 更多