python 3 csv data structure problems
Question: I have a csv file like this

    
    
    Category    Subcategory
    -----------------------
    cat         panther
    cat         tiger
    dog         wolf
    dog         heyena
    cat         lion
    dog         beagle
    

Im trying to write a script that outputs something like this (order not
important):

    
    
    animals = [
                  [['cat'], ['panther', 'tiger', 'lion']],
                  [['dog'], ['wolf', 'heyena', 'beagle']]
              ]
    

So far I am able to make a list of unique categories, and a list of unique sub
categories.

    
    
    for p in infile:
        if(p[0] not in catlist):
            catlist.append(p[0])
        if(p[1] not in subcatlist) :
            subcatlist.append(p[1])
    

But I am having trouble writing the logic that says "if Category 'cat' is in
animals[], but 'panther' is not in 'cat', append it."

Ive played with zip() and dict() some, but Im pretty much just flailing about
here. Fairly new to python. Using Python 3.


Answer: It is a lot easier to use dictionaries if you want to map keys to some values.
Especially convenient for building them is
[defaultdict](http://docs.python.org/2/library/collections.html#collections.defaultdict).

Assuming your infile splits the input lines on blank, the following should
help:

    
    
    from collections import defaultdict
    
    animals = defaultdict(list)
    
    for p in infile:
        animals[p[0]].append(p[1])
    

