Zach Santiago
Zach Santiago

Reputation: 381

Reading file and constructing dictionary

i am trying to read a comma delimited file and convert it into a dictionary so that it ends up in the following format

{'CpE' : CSE 2315,'CpE' : 'CSE 2320'. 'CpE' : 'CSE 2441'..........,'CS' : CSE 2315, 'CS' : CSE 2320}

so all i want to do is store each line in a dictionary with the degree being the key, and the class being the value

the file being read is

CpE,CSE 2315
CpE,CSE 2320
CpE,CSE 2441
CpE,CSE 3320
CpE,CSE 3442
CpE,EE 2440
CpE,MATH 1426
CS,SE 2315
CS,CSE 2320
CS,CSE 3320
CS,CSE 4303
CS,CSE 4305
CS,CSE 4308
CS,MATH 1426

the code i wrote to try to do this is... fp being the file

majors = {}
    for line in fp :
        (degree, course) = line.strip().split(',')
        majors[degree] = course
    print majors

what i get is

{'CS': 'MATH 1426', 'CpE': 'MATH 1426'}

it seems its only grabbing the last value of each degree/key. why?

Upvotes: 1

Views: 70

Answers (3)

mdml
mdml

Reputation: 22912

A key can map to only one value in a dictionary. As a result, you are constantly overwriting the single course for each major.

If you want to make a dictionary that maps each degree to a list of courses, you can easily do this using collection's defaultdict:

>>> from collections import defaultdict
>>> majors = defaultdict(list)
>>> fp = open("file.txt")
>>> for line in fp:
...     (degree, course) = line.strip().split(',')
...     majors[degree].append( course )
... 
>>> majors
defaultdict(<type 'list'>, {'CS': ['SE 2315', 'CSE 2320', 'CSE 3320', 'CSE 4303',
                                   'CSE 4305', 'CSE 4308', 'MATH 1426'],
                            'CpE': ['CSE 2315', 'CSE 2320', 'CSE 2441', 'CSE 3320',
                                    'CSE 3442', 'EE 2440', 'MATH 1426']
                           })

Upvotes: 1

musical_coder
musical_coder

Reputation: 3896

Dictionaries only map a single value to each key. What you should do here is map a list of courses to each key.

Upvotes: 2

Ryan O&#39;Donnell
Ryan O&#39;Donnell

Reputation: 617

It's because you're assigning it to the same key. You need to use a unique key for each value in your dictionary.

Upvotes: 1

Related Questions