Python: Appending to lists as keys within a dictionary
Question: 
    def classify(kingdom, species):
    """ (list of str, list of str) -> dict
    
    classifies each of the species in the right class in the format of a dictionary
    PRECONDITION: len(kingdom) = len(species)
    
    >>>classify(['Animal', 'Animal', 'Plant', 'Protist'], ['Dog', 'Cat', 'Daffodil', 'Plankton'])
    {'Animal' : ['Dog', 'Cat'], 'Plant' : ['Daffodil'], 'Protist' : ['Plankton']}
    """"
    

I am trying to complete this function; however, i do not know how to assign a
variable to a dictionary that uses lists as the values, nor do I know how to
add new values to the list.

So far this is my attempt

    
    
    def classify(kingdom, species):
    d = {}
    for j in range(len(kingdom)):
        d[kingdom[j]] = []
    for k in range(len(species)):
        d[kingdom[k]].append(species[k])
    return d
    

For some reason in returns the incorrect result.

    
    
    >>>classify(['Animal', 'Animal', 'Plant', 'Protist'], ['Dog', 'Cat', 'Daffodil', 'Plankton'])
    {'Protist': ['Dog', 'Cat', 'Daffodil', 'Plankton'], 'Plant': ['Dog', 'Cat', 'Daffodil', 'Plankton'], 'Animal': ['Dog', 'Cat', 'Daffodil', 'Plankton']}
    


Answer: Two problems.

First, everywhere you're using `kingdom[1]`, you should just be using
`kingdom`. Seems like you used to have a function that took a single list
containing two sublists, and you didn't update the code to correspond to the
new signature.

Second, doing `d[kingdom[j]] = b` will cause all values in `d` to point to the
exact same list. Appending to one of them will cause all the other ones to be
appended to as well. Just assign a brand new list each time.

    
    
    def classify(kingdom, species):
        d = {}
        for j in range(len(kingdom)):
            d[kingdom[j]] = []
        for k in range(len(species)):
            d[kingdom[k]].append(species[k])
        return d
    
    print classify(['Animal', 'Animal', 'Plant', 'Protist'], ['Dog', 'Cat', 'Daffodil', 'Plankton'])
    

Result:

    
    
    {'Plant': ['Daffodil'], 'Protist': ['Plankton'], 'Animal': ['Dog', 'Cat']}
    

* * *

Bonus: You may find it worthwhile to refactor your code. You can eliminate the
first loop in your function if you make `d` a `collections.defaultdict`; you
won't need to set up the lists, since they'll be created by default.

    
    
    from collections import defaultdict
    def classify(kingdom, species):
        d = defaultdict(list)
        for k in range(len(species)):
            d[kingdom[k]].append(species[k])
        return d
    

And you can make the second loop arguably more clear if you iterate through
the lists' elements directly instead of iterating through their indices.

    
    
    from collections import defaultdict
    def classify(kingdom, species):
        d = defaultdict(list)
        for name, kind in zip(species, kingdom):
            d[kind].append(name)
        return d
    

