1

Looking at the print statements in the following format, it's also required to include any new countries and population entered as input. I can make the code to show an appended dictionary in a dict format but having a hard time showing in the following format. What am I doing incorrectly?

Expected Output:

   Vatican has Population 800
   Vatican has Population 10200
   ...
def main():
        countryPop = {'Vatican': 800, 'Tuvalu': 10200, 'Nauru': 11000, 'Palau': 17900,
                      'San Marino': 33420, 'Monaco': 38300, 'Marshall Islands': 55500}

        # while loop to repeat the input request and population display until 0 is entered
        while True:
            ctry = input('Enter country:')
            population = countryPop.get(ctry)
            print('Population:',population)
            if ctry == '0':
                break

            # Else if Loop meant to activate if a country unknown to the original dictionary is entered
            elif ctry not in countryPop:
                popIn = input("Country Pop:")
                countryPop[ctry] = popIn

        # printing the new list after breaking from the loop
        for ctry in countryPop:
            print(str(ctry)+" has population "+str(popIn))
    if __name__ == '__main__':
        main()
1
  • replace str(popIn)with countryPop.get(ctry) in the last print statement. Commented Jan 28, 2020 at 11:57

2 Answers 2

2

You can use the for key in dict syntax to iterate over a dictionary's keys. Then, inside your loop, you can use dict[key] to read what's saved in that key. So the following would work:

countryPop = {'Vatican': 800, 'Tuvalu': 10200, 'Nauru': 11000, 'Palau': 17900,
                      'San Marino': 33420, 'Monaco': 38300, 'Marshall Islands': 55500}

for key in countryPop:
    print(key + " has Population " + str(countryPop[key]))

Output:

Palau has Population 17900

Tuvalu has Population 10200

Vatican has Population 800

San Marino has Population 33420

Marshall Islands has Population 55500

Monaco has Population 38300

Nauru has Population 11000

Sign up to request clarification or add additional context in comments.

1 Comment

You may want to read about the others available dict methods - like dict.items() for example.
2

This will print what you want

for ctry, pop in countryPop.items():
    print(f"{ctry} has population {pop}")

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.