【问题标题】:AttributeError: 'str' object has no attribute 'append' error when i tried to add list as value for a key in dictionary pythonAttributeError:当我尝试将列表添加为字典python中键的值时,'str'对象没有属性'append'错误
【发布时间】:2020-09-14 11:59:34
【问题描述】:

我正在尝试做一个程序,试图找出是否可以使用给定的输入形成二叉树。

def main():
    children={}
    parents={}
    possible=True
    tup=input("enter the tuples seperated by commas")
    tup=tup.replace("(","")
    tup=tup.replace(")","")
    data=tup.split(" ")
    print(len(data))
    for x in range(0,len(data)):
        child,parent=data[x].split(",")
        if parent in parents :
            parents[parent].append()
        else:
            parents[parent]=child
        if len(parents[parent])>2:
           possible=False
           break
        if child in children:
            possible=False
            break
        else:
            children[child]=parent
        if possible==True:
            print("BINARY TREE POSSIBLE")
        else:
            print("BINARY TREE NOT POSIBLE")
if __name__=="__main__":
    main()

问题出在这一行:

parents[parent].append()

在第 37 行它说:

AttributeError: 'str' object has no attribute 'append' 如何添加列表 作为python字典中键的值

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    您正在尝试将某些内容附加到与键“父”相对应的字符串。为了将列表作为 dict 的值,您需要将列表设置为值,就像使用字符串一样。

    my_list[key] = ["item1", "item2"]

    【讨论】:

    • hii 感谢您的回复,我通过在进入循环之前添加 parents[parent]=[] 解决了这个问题。还有其他方法可以做到这一点
    猜你喜欢
    • 2022-01-14
    • 2015-03-08
    • 2018-08-03
    • 2018-09-01
    • 1970-01-01
    • 2015-02-17
    • 2018-05-16
    • 2023-03-05
    • 2020-09-28
    相关资源
    最近更新 更多