简体   繁体   English

在 Python 中将字典输出为字符串

[英]Dictionary Output as String in Python

Looking at the print statements in the following format, it's also required to include any new countries and population entered as input.查看以下格式的打印语句,还需要包括作为输入输入的任何新国家和人口。 I can make the code to show an appended dictionary in a dict format but having a hard time showing in the following format.我可以使代码以dict格式显示附加字典,但很难以以下格式显示。 What am I doing incorrectly?我做错了什么?

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()

You can use the for key in dict syntax to iterate over a dictionary's keys.您可以for key in dict语法中使用for key in dict来迭代字典的键。 Then, inside your loop, you can use dict[key] to read what's saved in that key.然后,在您的循环中,您可以使用dict[key]读取保存在该键中的内容。 So the following would work:因此,以下将起作用:

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]))

Output:输出:

Palau has Population 17900帕劳有人口 17900

Tuvalu has Population 10200图瓦卢有人口 10200

Vatican has Population 800梵蒂冈有人口 800

San Marino has Population 33420圣马力诺有人口 33420

Marshall Islands has Population 55500马绍尔群岛有人口 55500

Monaco has Population 38300摩纳哥有人口 38300

Nauru has Population 11000瑙鲁有人口 11000

This will print what you want这将打印您想要的内容

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM