简体   繁体   English

Python:使用FOR Loop插入字典

[英]Python: Inserting into dictionary using FOR Loop

i have searched through the forum and can't understand if i can use the following construct to insert new entries into my Python Dictionary...without turning it into a list. 我已经在论坛中搜索过,无法理解是否可以使用以下结构将新条目插入到我的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)

The output is as follows: 输出如下:

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'}

Why does ONLY Mary:15 go in, and none of the others? 为什么只有Mary:15进来,而没有其他人进来?

thanks/ 谢谢/

Its because you do pupils_dictionary = {} 这是因为您执行了瞳孔数= {}

Inside your loop, on every loop, its value get reset to {} 在循环中,在每个循环中,其值都将重置为{}

suggestion : 建议:

use raw_input instead of input 使用raw_input代替输入

so this code should work : 所以这段代码应该工作:

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)

You create the dictionary anew with each loop: 您可以在每个循环中重新创建字典:

for x in range(3):    
   pupils_dictionary = {}
   new_key =input('Enter new key: ')
   ...

Instead, create it once outside the loop: 而是在循环外创建一次:

pupils_dictionary = {}
for x in range(3):    
   new_key =input('Enter new key: ')
   ...

You redefine the dictionary as empty during every pass through the loop. 您在遍历循环时将字典重新定义为空。 The code should be. 代码应该是。

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

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

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