【问题标题】:AttributeError: 'dict' object has no attribute 'append' and tests failingAttributeError:“dict”对象没有属性“append”并且测试失败
【发布时间】:2020-10-16 07:58:52
【问题描述】:

有没有人知道为什么这段代码在运行时会显示“AttributeError: 'dict' object has no attribute '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[k].append(default_value)。或者,您想要的 dict 方法是 .update({key: value})

标签: dictionary append


【解决方案1】:

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

dictionary[key] = default_value

【讨论】:

  • 太好了,它解决了错误,我只需要tuple 我的所有列表。但是现在测试失败了,我不知道为什么
  • 您知道如何通过这些测试吗?
猜你喜欢
  • 2019-03-31
  • 2018-06-22
  • 1970-01-01
  • 2020-11-07
  • 2019-03-11
  • 2016-02-11
  • 2018-03-17
  • 2018-09-02
  • 2021-01-30
相关资源
最近更新 更多