Python中作为字符串的字典输出

2024-10-06 11:19:25 发布

您现在位置:Python中文网/ 问答频道 /正文

查看以下格式的打印报表,还需要包括输入的任何新国家和人口。我可以让代码以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()

Tags: thetoloopinputifmain格式has
2条回答

这将打印您想要的内容

for ctry, pop in countryPop.items():
    print(f"{ctry} has population {pop}")

您可以使用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]))

输出:

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

相关问题 更多 >