Dictionary 属性错误:';dict';对象没有属性';追加';测试失败

Dictionary 属性错误:';dict';对象没有属性';追加';测试失败,dictionary,append,Dictionary,Append,有人知道为什么运行的代码会说“AttributeError:'dict'对象没有属性'append'”。还有,如何让这些测试通过?我试图帮助一位朋友,但我们都是Python新手 def complete_with_default(dictionary, keys, default_value): """If `dictionary` is missing a key from `keys`, the function adds the key to

有人知道为什么运行的代码会说“AttributeError:'dict'对象没有属性'append'”。还有,如何让这些测试通过?我试图帮助一位朋友,但我们都是Python新手

def complete_with_default(dictionary, keys, default_value):
    """If `dictionary` is missing a key from `keys`, the function
    adds the key to `dictionary` with a default value.
    
    Changes the dictionary in-place and returns `None`.
    """
    for k in keys:
        if k in dictionary:
            dictionary.append(default_value)

d1 = {'a': 1, 'b' : 2}
ks1 = ['c', 'd']
def_val1 = None

d2 = {'a': 1, 'b' : 2}
ks2 = ['b', 'c']
def_val2 = None

d3 = {'a': 1, 'b' : 2}
ks3 = ['a', 'b', 'c']
def_val3 = 321

d4 = {'a': 1, 'b' : 2}
ks4 = []
def_val4 = None

complete_with_default(d1, ks1, def_val1)
complete_with_default(d2, ks2, def_val2)
complete_with_default(d3, ks3, def_val3)
complete_with_default(d4, ks4, def_val4)


def run_test(obtained, expected, number):
    if len(obtained) != len(expected):
        print("Test ", number, " failed!")
        print(obtained)
        return
        
    if obtained != expected:
        print("Test ", number, " failed!")
        print(obtained)
        return
    
    print("Test ", number, " succeeded!")
    
run_test(d1, {'a': 1, 'b' : 2, 'c': None, 'd': None}, 1)
run_test(d2, {'a': 1, 'b' : 2, 'c': None}, 2)
run_test(d3, {'a': 1, 'b' : 2, 'c': 321}, 3)
run_test(d4, {'a': 1, 'b' : 2}, 4)

看起来您正在使用下标(
[]
)运算符:

dictionary[key]=默认值

看起来您正在使用下标(
[]
)运算符:

dictionary[key]=默认值

太好了,它解决了错误,我只需对所有列表进行
tuple
即可。但是现在测试失败了,我不知道你为什么知道如何让这些测试通过?太好了,它解决了错误,我只需要对所有列表进行
tuple
。但是现在测试失败了,我不知道你为什么知道如何让这些测试通过?试试
dictionary[k].append(默认值)
。或者,您希望在dict上使用的方法是
.update({key:value})
尝试
字典[k].append(默认值)
。或者,您想要在dict上使用的方法是
.update({key:value})