0

I have a pickled file which contains the names and 3 scores of each student in a class. So far using:

import pickle
filename="friendlist.data"
f=open('Class6B.txt','rb')
storedlist=pickle.load(f)
for i in storedlist:
    print(i)`

I can only print out the names, how would i print out the 3 scores attached to each student?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Rutwb2
  • 147
  • 2
  • 2
  • 7

1 Answers1

0

If storedlist is a dictionary, then looping over the dictionary with for i in storedlist will set i to the keys of the dictionary. If you want to print the values instead, iterate over the values specifically with:

for i in storedlist.values():
    print(i)

To get both the keys and the values, use:

for key, value in storedlist.items():
    print "{} --> {}".format(key, value)

Here, items() gives you the keys and values in a tuple, which can be directly unpacked into two separate variables (key and value above).

Also, if the dictionary has many items, it may be more efficient for you to use itervalues() or iteritems() to generate the values in the loop without fully building a list as described further here.

Community
  • 1
  • 1
mattsilver
  • 4,386
  • 5
  • 23
  • 37