AttributeError:'dict'对象没有属性'append'并且测试失败

时间:2020-06-25 18:58:48

标签: 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 `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)

1 个答案:

答案 0 :(得分:0)

好像您要使用下标(Time Value 2020-04-24 9:12:01 $2.50 2020-04-24 9:13:12 $2.56 2020-04-24 9:14:08 $2.51 )运算符:

[]