1

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?

1
  • 1
    Keys in a dictionary are unique... So are you after (CS + MATH) -> 1426, or for CS, a list of MATH 1426, SE 2315, etc.... Commented Nov 18, 2013 at 17:02

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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']
                           })

1 Comment

You can do this with the built in dict as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.