Dictionaries and files in python
Question: Hey guys first time question here.

I'm trying to figure out how to create a dictionary containing keys as ID's,
and values as another dictionary containing scores for homework essays and
exam's for that individuals ID.

Example:

    
    
    {"173-25-6389":
        {
            "hw":[94,89,92,73], 
            "quiz":[45,36,42,50,22,27,40,41], 
            "exam":[135,127]
        },
    .....
    }
    

These numbers are being pulled from separate files representing the categories
and are each matched with their corresponding ID.

I have 4 files to work with and one of them just contains the IDs which I
think I will apply to the keys in the larger dictionary.

My main issue is that inside of the files, each line is written like:

> 173-25-6389 61

So it's the `id` plus a `space` and then the `score`. I'm not sure how to run
through the file and search for the other scores that have the same ID.

I'm just a bit confused as to how to find a list of the scores, and then add
that to a dictionary as the value for the larger dictionary containing the
ID's. Any insight as to how to precede would really be amazing and if you need
me to elaborate more let me know.

I have only been coding for about a year so go easy on me. Thanks


Answer: So let's assume you already know how to open the file and read it line-by-
line. For each line you have an id and a score, but you don't know if the
score already exists in your result dict. Frankly, you'd rather not care.
Enter
[defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict).
It guarantees you a useful value even if the particular key doesn't exist.

    
    
    from collections import defaultdict
    …
    result = defaultdict(dict) # an undefined key will map an empty dict
    for line in scorefile:
        id, score = line.split()
        result[id]['hw'] = score
    

But wait, that will overwrite our 'hw' key with a single score! We wanted a
list!

Let's double down on this defaultdict.

    
    
    # an undefined key will map a defaultdict
    # whose undefined keys will map an empty list
    result = defaultdict(lambda: defaultdict(list))
    for line in scorefile:
        id, score = line.split()
        result[id]['hw'].append(score)
    

Now, you didn't say how we were to tell homework from exam scores, so I'll
leave that bit up to you…

