为了账号安全,请及时绑定邮箱和手机立即绑定

Python AttributeError:“str”对象没有属性“items”

Python AttributeError:“str”对象没有属性“items”

白板的微信 2022-06-22 18:47:55
在以下代码中:grades = {    ("DD1", 1) : 45,    ("DD1", 2) : 75,    ("DD1", 3) : 25,    ("DD1", 4) : 65,    ("DD2", 1) : 85,    ("DD2", 2) : 40,    ("DD2", 3) : 70,    ("DD2", 4) : 80,    }def listGrades(dataBase, group):    list_of_score = []    for key, value in dataBase.items():            if key[0] == group:                list_of_score.append(value)    return list_of_scoredataBase = input("Which database?")group = input("which group?")print(listGrades(dataBase, group))调试后,我得到这个:Which database?gradeswhich group?DD1Traceback (most recent call last):  File "C:\Users\DuckyGoh\Desktop\1003\tt3.py", line 51, in <module>    print(listGrades(dataBase, group))  File "C:\Users\DuckyGoh\Desktop\1003\tt3.py", line 43, in listGrades    for key, value in dataBase.items():AttributeError: 'str' object has no attribute 'items'有人可以教育我我的错误以及如何解决这个问题。
查看完整描述

1 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

if sys.version_info >= (3,):

    def input(__prompt: Any = ...) -> str: ...

else:

    def input(__prompt: Any = ...) -> Any: ...

    def intern(__string: str) -> str: ...

从 python 3 开始,输入被接受为字符串。对于 python2,上面可以接受数据库作为全局对象中可用的对象。


grades = {

    ("DD1", 1) : 45,

    ("DD1", 2) : 75,

    ("DD1", 3) : 25,

    ("DD1", 4) : 65,


    ("DD2", 1) : 85,

    ("DD2", 2) : 40,

    ("DD2", 3) : 70,

    ("DD2", 4) : 80,

}


dataBases = {

    'grades': grades

}


def listGrades(dataBase, group):

    list_of_score = []

    for key, value in dataBase.items():

        if key[0] == group:

            list_of_score.append(value)

    return list_of_score


dataBase = input("Which database?")

group = input("which group?")


dataBase = dataBases.get(dataBase, {})


print(listGrades(dataBase, group))


查看完整回答
反对 回复 2022-06-22
  • 1 回答
  • 0 关注
  • 222 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号