Moh'd H
Moh'd H

Reputation: 247

Function not returning the Value of its Key

I'm writing a function that constructs a dictionary from a given file. The file contains lines of data like: 7576240,Sigrid,Rahn. The number is an ID, and the rest is a first and second name. my task is to create a dictionary with the ID as a Key and the the first and last name as a Value in a tuple format. I have managed to do so, but when i try to do this :

students_dict = read_class_from_file('class1.txt')
print(students_dict['7576240'])

it returns the:

2365568 : ('Josef', 'Krten')
3544826 : ('Bernadene', 'Klimas')
5215521 : ('Florie', 'Starkebaum')
6914206 : ('Minnaminnie', 'Sridhar')
7576240 : ('Sigrid', 'Rahn')
8963113 : ('Sharri', 'Benyon')
Traceback (most recent call last):
  File "<string>", line 2, in <fragment>
builtins.TypeError: 'NoneType' object is not subscriptable

I think the dictionary is working fine, untill i call a Key to get its Value,can someone help with this?

My code:

def read_class_from_file(filename):
    ''' function reads all data in (filename) and returns a dictionary '''
    dictionary = {}
    lines = []
    data = [line.strip() for line in open(filename, 'r')]
    for line in data[1:]:
        lines += [line.split(",")]
    for lina in lines:
        dictionary[lina[0]] = (lina[1], lina[2])
    for key in sorted(dictionary.keys()):
        print("{0} : {1}".format(key, dictionary[key]))

Upvotes: 1

Views: 125

Answers (1)

VMrx
VMrx

Reputation: 43

You're not returning anything from your function. You'll have to add

return dictionary

to the end of your definition of read_class_from_file. Since it doesn't currently return anything, students_dict is None.

Upvotes: 1

Related Questions