查看以下格式的打印报表,还需要包括输入的任何新国家和人口。我可以让代码以dict
格式显示附加词典,但很难以以下格式显示。我做错了什么
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()
这将打印您想要的内容
您可以使用
for key in dict
语法来迭代字典的键。然后,在循环中,可以使用dict[key]
读取该键中保存的内容。因此,以下措施将起作用:输出:
相关问题 更多 >
编程相关推荐