dictionary - 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)
解决方案
看起来您正在寻找使用下标 ( []
) 运算符:
dictionary[key] = default_value
推荐阅读
- amazon-web-services - RPI 的 AWS 实例类型
- python - 在 Python 中使用元组绘制有向图
- reactjs - 尝试从 Firestore 获取和更新集合时发现“文档集合中未定义”
- objective-c - UICollectionview 更改项目排序 Objective-C
- kubernetes - Nginx 反向代理背后的 Botpress
- javascript - 如何将我的 JavaScript 库代码与 webpack 打包成 jQuery 一样可扩展?
- c++ - 使用openthread而不使用线程协议的CoAP应用程序开发
- google-apps-script - Google APP 脚本将值转换为 TRUE 以设置 MultipleChoice 答案键
- mysql - 如何找到客户在特定日期范围内的最大点击次数?
- sql - 关于使用存储在记录中的数据库名称的跨数据库子查询