[英]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.