Lapochka
Lapochka

Reputation: 9

Using a class as a dictionary value in python

I'm new to to Python and could use some help. I'm trying to use several class parameters as a dictionary value and I don't know how to return the value with the class's parameter variables. Here's what I have so far:

import random

class Movie:

  def __init__(self, title)
    self.__title=title



  def __str__(self):
    return 

questions={
  "May the Force be with you.":Movie("Star Wars: Episode IV - A New Hope",1977,"George Lucas",["Sci-fi","Action"],121,"PG")
}



print("Here's a random selection of", 2,"questions:")
rset = random.sample(list(questions), 2)
print()

#Accumulator Start
total=0
qt=0
#Question Loop
for q in rset:
    qt+=1
    print("Question #",qt,":",q)
    ans=input('Answer: ')
    if ans.casefold()==Movie(self.__title).casefold():
      print('Correct! The answer is:' ,questions[q])
      print()
      total+=1
      
    else:
      print("Incorrect. The answer is:", questions[q])
      print()

I'd like the questions[q] to return class Movie if possible. Any suggestions?

Upvotes: 0

Views: 130

Answers (2)

leaf_soba
leaf_soba

Reputation: 2518

  • You can't use self outside a class.
  • Just use questions[q] you can return a instance of Moive class, no need to return a class itself in the situation.
  • The attribute start with __ treat as private in python, which can't access from outside.

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 

questions={
  "May the Force be with you.":Movie("Star Wars: Episode IV - A New Hope",1977,"George Lucas",["Sci-fi","Action"],121,"PG"),
  "test":Movie("test_title",1978,"test_director",["test1","test2"],99,"test_rating")
}

#Determine quantity
quantity=int(input("How many questions? "))
print()


print("Here's a random selection of", quantity,"questions:")
rset = random.sample(list(questions), quantity)
print()

#Accumulator Start
total=0
qt=0

#Question Loop
for q in rset:
    qt+=1
    print(f"Question # {qt}:{q}")
    ans=input('Answer: ')
    if ans.casefold()==questions[q].title.casefold():
      print('Correct! The answer is:' ,questions[q].title.casefold())
      print()
      total+=1
      
    else:
      print("Incorrect. The answer is:", questions[q].title.casefold())
      print()

result:

How many questions? 2

Here's a random selection of 2 questions:

Question # 1:test
Answer: a
Incorrect. The answer is: test_title

Question # 2:May the Force be with you.
Answer: Star Wars: Episode IV - A New Hope
Correct! The answer is: star wars: episode iv - a new hope

Upvotes: 1

Zichzheng
Zichzheng

Reputation: 1280

Yes, that is possible. However, Python dicts are unordered. So return the value of a dict via index does not make sense, But if you want, you can do:

value_at_index = dic.values()[index]

Instead, you will want to return the value via key, for your code:

value = questions["May the Force be with you."]

but right now, for your str method, you did not return anything. Keep in mind that str should return a string. For example you want to return the title, you code would be like:

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])

Which will output:

{'May the Force be with you.': <__main__.Movie object at 0x00000268062039C8>}
Star Wars: Episode IV - A New Hope

Process finished with exit code 0

Upvotes: 0

Related Questions