Saturday, April 30, 2016

Using Python3

Do you need to start a virtual environment with python 3 instead of python 2.x? I'll show you how.

I am not going to show you how to change the python version of an existing virtual environment today, so if you have already started a virtual environment in python 2.x, please delete it and create a new one from scratch using the directions below.

First, let's make sure we have python3 installed. Check where your python3 is located:
which python3

A path should come up. However, if your system can't find it, that means you don't have it installed. Use Homebrew (brew install python3) and you should be good to go.

Now that we know where our python3 is installed, let's create a virtual environment that uses python3.

mkvirtualenv mycoolenv -p /usr/local/bin/python3

As you can see above, my python3 was located at /usr/local/bin/python3, but substitute yours with your particular path.

And there you have it! You have now created a virtual environment called mycoolenv that will use python3.



Python Collections & Recollections

I collected lots of stuff as a kid—mainly rocks, pencils, bouncy balls, postal stamps and stickers. Now that I live in a tiny apartment, I don't have anywhere to hoard keep any collections.

Do you feel my pain? Do you want more collections in your life? Well, good news: no matter how small your space is, you always have room to squeeze Python's collections module into your life. The documentation is very thorough, so I suggest you check it out. What follows is a more beginner friendly intro to collections if you've never used this module before.

from collections import Counter



No counter space in your kitchen? That's unfortunate. In Python, you'll always have space to import counter objects! Just type from collections import Counter and you're good to go.

After you create a Counter object with Counter(), you can update that object with items from a list, and it will create a dictionary that stores that items of that list as keys and the number of times that item appears. You can also add two counter objects:
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2, c=1)
>>> c+d

Counter({'a': 4, 'b': 3, 'c': 1})

It's like having Count von Count on speed dial.

Count von Count to the rescue!

from collections import defaultdict
defaultdict is awesome! You can initialize it as a an int if you want to count stuff, or as a list if you want to keep appending items.

That means instead of:
def create_record(list1):
    """Iterate through list1 and return a dictionary, final_dict, which has all items from list1 as keys, and their frequencies as values.
    """
    final_dict = dict()
    for item in list1:
        if final_dict[item]:
            final_dict[item] += 1
        else:
            final_dict[item] = 1
    return final_dict

You can just write:
from collections import defaultdict
def create_record(list1):
    """Iterate through list1 and return a dictionary, final_dict, which has all items from list1 as keys, and their frequencies as values.
    """
    final_dict = defaultdict(int)
    for item in list1:
        final_dict[item] += 1
    return final_dict


from collections import OrderedDict
An OrderedDict allows you to maintain a dictionary that is ordered by its keys or values.
Let's pretend for a sec that we are in charge of inventory for a Peanuts store.

>>> from collections import OrderedDict
>>> my_dict = {'snoopy': 100, 'woodstock': 22, 'charlie_brown': 35, 'lucy': 60, 'linus': 77, 'belle': 101}
>>> OrderedDict(sorted(my_dict.items(), key=lambda k: k[0]))
OrderedDict([('belle', 101), ('charlie_brown', 35), ('linus', 77), ('lucy', 60), ('snoopy', 100), ('woodstock', 22)])
>>> OrderedDict(sorted(my_dict.items(), key=lambda k: k[1]))

OrderedDict([('woodstock', 22), ('charlie_brown', 35), ('lucy', 60), ('linus', 77), ('snoopy', 100), ('belle', 101)])
>>> OrderedDict(sorted(my_dict.items(), key=lambda k: k[1], reverse=True))
OrderedDict([('belle', 101), ('snoopy', 100), ('linus', 77), ('lucy', 60), ('charlie_brown', 35), ('woodstock', 22)])


By using OrderedDict, we can quickly see which characters we have, ordered alphabetically (lambda k: k[0]), or ordered by how much inventory of each character we have (lambda k: k[1]). You can sort it the other way by adding "reverse=True".

Snoopy thinks he has the upper hand, but he has no idea that Belle is beating him in our OrderedDict.

Now the time has come for you to experiment with collections on your own. Have fun!