首页 > 解决方案 > AttributeError:“dict”对象没有属性“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 `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)

标签: dictionaryappend

解决方案


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

dictionary[key] = default_value

推荐阅读