<p>是的,这是可能的。然而,Python指令是无序的。因此,通过索引返回dict的值没有意义,但如果需要,可以执行以下操作:</p>
<pre><code>value_at_index = dic.values()[index]
</code></pre>
<p>相反,您希望通过键返回代码的值:</p>
<pre><code>value = questions["May the Force be with you."]
</code></pre>
<p>但是现在,对于您的<strong>str</strong>方法,您没有返回任何内容。请记住,<strong>str</strong>应该返回一个字符串。例如,如果要返回标题,代码如下:</p>
<pre><code>import random
class Movie:
def __init__(self, title, releaseYear, director, genre, length, rating):
self.__title = title
self.__releaseYear = releaseYear
self.__director = director
self.__genre = genre
self.__length = length
self.__rating = rating
def __str__(self):
return self.__title
questions = {
"May the Force be with you.": Movie("Star Wars: Episode IV - A New Hope", 1977, "George Lucas",
["Sci-fi", "Action"], 121, "PG")
}
# Determine quantity
print(questions)
for keys in questions:
print(questions[keys])
</code></pre>
<p>这将输出:</p>
<pre><code>{'May the Force be with you.': <__main__.Movie object at 0x00000268062039C8>}
Star Wars: Episode IV - A New Hope
Process finished with exit code 0
</code></pre>