[英]Dictionary Output as String in Python
查看以下格式的打印语句,还需要包括作为输入输入的任何新国家和人口。 我可以使代码以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
语法中使用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
这将打印您想要的内容
for ctry, pop in countryPop.items():
print(f"{ctry} has population {pop}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.