我想在课堂上打印字典中的键

Moz*_*ein 0 python dictionary python-3.x

我正在尝试打印作为字典中存储的键的行星名称,但是我什么都没有,只是空间

这是我的代码:

class planets:
    def __init__(self, aDict):
        self.aDict = aDict
    def __str__(self):
        for key in self.aDict.keys():
            print(key)



aDict = {"Sun": 1000, "Mercury": 10, "Earth": 60, "Mars": 50, "jupiter": 100}
p = planets(aDict)
Run Code Online (Sandbox Code Playgroud)

ACh*_*ion 5

你需要实际打印p并且__str__需要返回一个字符串,例如:

    def __str__(self):
        return ' '.join(sorted(self.aDict, key=self.aDict.get))

aDict = {"Sun": 1000, "Mercury": 10, "Earth": 60, "Mars": 50, "jupiter": 100}
p = planets(aDict)
print(p)
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`return'\n'.join(sorted(self.aDict,key = self.aDict.get))`. (2认同)