简体   繁体   中英

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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