查看以下格式的打印语句,还需要包括输入的所有新国家和人口。我可以使代码以某种dict
格式显示附加字典,但很难以以下格式显示。我做错了什么?
预期产量:
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()
您可以使用for key in dict
语法来迭代字典的键。然后,在循环中,您可以dict[key]
用来读取该键中保存的内容。因此,以下方法将起作用:
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]))
输出:
帕劳人口17900
图瓦卢有人口10200
梵蒂冈人口800
圣马力诺人口33420
马绍尔群岛人口55500
摩纳哥人口38300
瑙鲁有人口11000
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句