天天看點

python loop怎麼用_Python:使用FOR Loop插入字典

python loop怎麼用_Python:使用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.

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?

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

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)