字典在Python中以字符串形式输出

meag_a

查看以下格式的打印语句,还需要包括输入的所有新国家和人口。我可以使代码以某种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()
伊斯梅尔·帕迪利亚(Ismael Padilla)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Python中以字符串形式逐步输出字符

如何在python的字符串(句子)中打印函数返回的字典输出?(处理中)

修改python字典中的字符串

从Python中的字符串创建字典

Python中的字符串到字典

Python中的字符串和字典

Python:如何以表格形式输出字符串

在Go中以短字符串形式输出UUID

为什么jsp中的“ $ {}”标签以字符串形式输出

删除可选的字符串形式字典

以字符串形式获取函数的输出

在Python中将具有字典式表示形式的字符串转换为字典

将字典的字符串表示形式转换为Swift中的字典?

使用字典中的变量值执行以字符串形式编写的数学表达式(python)

python中字典字符串中的变量

如何遍历字典列表的字符串表示形式的字典?

将字典的字符串表示形式转换为字典?

将字典的字符串表示形式转换为字典

如何比较字典和字符串并输出字典?

Python字符串:如何查询列表中的字典,这些字典在字典中

使用Python中的字符串字典替换某些短语中的某些字符串

如何正确拆分字符串以在python中创建字典?

多行字符串到 Python 2.7 中的元组字典

在Python字典中匹配不完整的字符串

Python使用字典替换字符串中的变量

Python 中字典序最小的字符串是什么?

python:替换嵌套字典中的字符串

将 XML 字符串插入 Python 字典值中

从Python字典中的列表中提取字符串