Python:使用FOR循环插入字典 [英] Python: Inserting into dictionary using FOR Loop
本文介绍了Python:使用FOR循环插入字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在论坛上进行了搜索,无法理解是否可以使用以下结构将新条目插入到我的Python词典中...而无需将其转换为列表.
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.
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'}
为什么只有玛丽:15进来,而没有其他人进来?
Why does ONLY Mary:15 go in, and none of the others?
谢谢/
推荐答案
是因为您这样做 studentss_dictionary = {}
Its because you do pupils_dictionary = {}
在循环中,在每个循环中,其值都将重置为{}
Inside your loop, on every loop, its value get reset to {}
建议:
使用raw_input代替输入
use raw_input instead of 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)
这篇关于Python:使用FOR循环插入字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文