我搜索了论坛,无法理解我是否可以使用以下构造将新条目插入到我的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'}
为什么只有玛丽:15进去,而其他人都不进去?
感谢/
答案 0 :(得分: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)
答案 1 :(得分:5)
您可以使用每个循环重新创建字典:
for x in range(3):
pupils_dictionary = {}
new_key =input('Enter new key: ')
...
相反,在循环外创建一次:
pupils_dictionary = {}
for x in range(3):
new_key =input('Enter new key: ')
...
答案 2 :(得分:0)
在每次循环中,您都会将字典重新定义为空。代码应该是。
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)