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()
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
This will print what you want
for ctry, pop in countryPop.items():
print(f"{ctry} has population {pop}")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.