Python:使用FOR循环插入字典

Tin*_*iny 1 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)
Run Code Online (Sandbox Code Playgroud)

输出如下:

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'}
Run Code Online (Sandbox Code Playgroud)

为什么只有玛丽:15进入,其他人都没有?

谢谢/

Fre*_*ult 6

因为你做pupils_dictionary = {}

在循环内部,在每个循环中,其值将重置为{}

建议:

使用raw_input而不是input

所以这段代码应该工作:

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)
Run Code Online (Sandbox Code Playgroud)


jon*_*rpe 5

您可以使用每个循环重新创建字典:

for x in range(3):    
   pupils_dictionary = {}
   new_key =input('Enter new key: ')
   ...
Run Code Online (Sandbox Code Playgroud)

相反,在循环外创建一次:

pupils_dictionary = {}
for x in range(3):    
   new_key =input('Enter new key: ')
   ...
Run Code Online (Sandbox Code Playgroud)