猿问

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

在以下代码中:


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_score


dataBase = input("Which database?")

group = input("which group?")


print(listGrades(dataBase, group))

调试后,我得到这个:


Which database?grades

which group?DD1

Traceback (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'

有人可以教育我我的错误以及如何解决这个问题。


白板的微信
浏览 223回答 1
1回答

人到中年有点甜

if sys.version_info >= (3,):&nbsp; &nbsp; def input(__prompt: Any = ...) -> str: ...else:&nbsp; &nbsp; def input(__prompt: Any = ...) -> Any: ...&nbsp; &nbsp; def intern(__string: str) -> str: ...从 python 3 开始,输入被接受为字符串。对于 python2,上面可以接受数据库作为全局对象中可用的对象。grades = {&nbsp; &nbsp; ("DD1", 1) : 45,&nbsp; &nbsp; ("DD1", 2) : 75,&nbsp; &nbsp; ("DD1", 3) : 25,&nbsp; &nbsp; ("DD1", 4) : 65,&nbsp; &nbsp; ("DD2", 1) : 85,&nbsp; &nbsp; ("DD2", 2) : 40,&nbsp; &nbsp; ("DD2", 3) : 70,&nbsp; &nbsp; ("DD2", 4) : 80,}dataBases = {&nbsp; &nbsp; 'grades': grades}def listGrades(dataBase, group):&nbsp; &nbsp; list_of_score = []&nbsp; &nbsp; for key, value in dataBase.items():&nbsp; &nbsp; &nbsp; &nbsp; if key[0] == group:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list_of_score.append(value)&nbsp; &nbsp; return list_of_scoredataBase = input("Which database?")group = input("which group?")dataBase = dataBases.get(dataBase, {})print(listGrades(dataBase, group))
随时随地看视频慕课网APP

相关分类

Python
我要回答