0
def file_read ():
  dictionary = {}
  state      = ""
  capital    = ""
  flag       = 0
  with open("state_capitals.txt","r") as f:
      for line in f:
        if flag == 0:
            state = line.rstrip('\n')
            flag = 1
        elif flag == 1:
            capital = line.rstrip('\n')
            flag = 0
        dictionary[state] = capital
  print(dictionary)

How would I use a while loop to make the dictionary instead of the for loop. Code works perfectly fine but professor insists I use a while loop.

2
  • You can store each line in a list and use while loop with index, which breaks if the index is equal or greater than the length of the list Commented Apr 4, 2021 at 6:32
  • There are over 28,000 search results for "for loop to while loop" when searching under the [python] tag; perhaps one of these existing Q&As will be helpful to you. Commented Apr 4, 2021 at 6:34

1 Answer 1

2
def file_read():
    dictionary = {}
    state = ""
    capital = ""
    flag = 0
    with open("state_capitals.txt", "r") as f:
        while True:
            line = f.readline()
            if not line:
                break
            if flag == 0:
                state = line.rstrip('\n')
                flag = 1
            elif flag == 1:
                capital = line.rstrip('\n')
                flag = 0
            dictionary[state] = capital
    print(dictionary)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.