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

时间:2019-10-12 15:59:18

标签: python

在以下代码中:

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'

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

1 个答案:

答案 0 :(得分:3)

[]

从python 3开始,输入被接受为字符串。对于python2,上面的代码可以接受dataBase作为全局变量中可用的对象。

if sys.version_info >= (3,):
    def input(__prompt: Any = ...) -> str: ...
else:
    def input(__prompt: Any = ...) -> Any: ...
    def intern(__string: str) -> str: ...