Skip to main content
 首页 » 编程设计

Python:使用 FOR 循环插入字典

2025年05月04日9lori

我在论坛中进行了搜索,但无法理解是否可以使用以下结构将新条目插入到我的 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)