3

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/

Steinar Lima
  • 7,644
  • 2
  • 39
  • 40
Tiny
  • 409
  • 2
  • 8
  • 20
  • Important thing to consider: what do you do when the user re-enters the same name?! Dictionaries can't have duplicate keys -- this is possibly better as a list of tuples. – Adam Smith Mar 11 '14 at 23:55
  • Why have you removed most of the question? – jonrsharpe Mar 12 '14 at 00:06
  • @user3396486 I rollbacked your edit since all of the answers here were posted based on your example (which you removed with your edit) – Steinar Lima Mar 12 '14 at 00:17

3 Answers3

10

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)
Frederic Nault
  • 986
  • 9
  • 14
6

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: ')
   ...
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1

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)
sabbahillel
  • 4,357
  • 1
  • 19
  • 36