King Eze
King Eze

Reputation: 1

For loops in Dictionaries

I am trying to use a for loop in a dictionary to represent an unknown about of statements that may need to be in the dictionary (based on the specified amount when stating the class). I was wondering what the syntax for that would be if there is any at all.

Earlier today a friend asked me to make a Choose Your Own Adventure game.

I was trying to use a for statement to get a page number that is called with the class. The pages are random so there is no way for me to know.

from time import sleep
from random import randint

def ClearSys():
  for i in range(0,100):
    print("\n")
class Book:
  def __init__(self,name,pages):

    #self.DeathPage#
    RandomPage=randint(2,pages)
    self.DeathPage=RandomPage
    del RandomPage

    #self.pages#
    self.pages=["Introduction Page"]
    for i in range(2,pages):
      if not i==self.DeathPage:
        self.pages.append("QuestionPage")
      else:
        self.pages.append("DeathPage")



    ####MAIN SECTION I WOULD LIKE TO HIGHLIGHT####
    ##Page number dictionary##
    self.PageNumberToType={
      0:"Introduction Page",
      for i in range(1,len(self.pages)):
        i:self.pages[i]
    }
    ########

I didn't really expect this to work, but I just wrote it out to see if it were possible.

Upvotes: 0

Views: 74

Answers (2)

Austin
Austin

Reputation: 26037

Because order is of little importance when it comes to dictionaries, you can do a dictionary-comprehension as well:

self.PageNumberToType = {i: self.pages[i]
                         for i in range(1, len(self.pages[i]))}

self.PageNumberToType.update({0: 'Introduction Page'})

Upvotes: 1

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

None that I know of; but why does it need to be inside the dictionary literal?

self.PageNumberToType = { 0:"Introduction Page" }

for i in range(1, len(self.pages)):
    self.PageNumberToType[i] = self.pages[i]

Upvotes: 1

Related Questions