Python:使用 FOR 循环插入字典

标签 python dictionary

我在论坛中进行了搜索,但无法理解是否可以使用以下结构将新条目插入到我的 Python 词典中...而无需将其转换为列表。

for x in range(3):    
   pupils_dictionary = {}
   new_key =input('Enter new key: ')
   new_age = input('Enter new age: ')
   pupils_dictionary[new_key] = new_age
print(pupils_dictionary)

输出如下:

Enter new key: Tim
Enter new age: 45
Enter new key: Sue
Enter new age: 16
Enter new key: Mary
Enter new age: 15
{'Mary': '15'}

为什么只有 Mary:15 进去了,而其他人都没有?

谢谢/

最佳答案

因为你有 pupils_dictionary = {}

在您的循环中,在每个循环中,它的值都会重置为{}

建议:

使用原始输入代替输入

所以这段代码应该可以工作:

pupils_dictionary = {}

for x in range(3):    
    new_key = raw_input('Enter new key: ')
    new_age = raw_input('Enter new age: ')
    pupils_dictionary[new_key] = new_age
print(pupils_dictionary)

关于Python:使用 FOR 循环插入字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339164/

相关文章:

python - 迭代字典,添加键和值

python - 导入模块中的全局变量

python - 我想在 DJANGO 上创建一个动态可编辑表格

java - 未知公式的包装函数

Python - 访问列表内字典内的字典

python - 在 A 列中搜索字典键的文本,如果找到则将 B 列设置为 Pandas 数据框中的字典值

python - 两个连续的 yield 语句如何在 python 中工作?

python - 在运行时修改小部件颜色而不覆盖样式表

python - 根据条件递归地将键添加到嵌套字典中

java - JDB 整数映射查找