In Praise of Order

Call me a control freak, but I like things to be well organized. Having worked with Python for the past year, I’ve been in a constant fight to retrieve data from dictionaries in the same order I entered them. Chalk it up to a laziness that kept me from asking the all-knowing, all-seeing oracle of information that is Google the simple question, “Well is there an ordered dictionary?”

Of course there is: OrderedDict.  And it makes life so much easier when trying to keep data in sequential order while having the key-value access of a dictionary.  I’ve just started playing with it and it doesn’t seem as flexible as a standard dictionary.  To sort by key, you need to do something like:

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
OrderedDict(sorted(d.items(), key=lambda t: t[0]))

Or by value with:

OrderedDict(sorted(d.items(), key=lambda t: t[1]))

But you can also load in a json file with a simple addition:

import json
from collections import OrderedDict
my_ordered_dict = json.loads(json_str, object_pairs_hook=OrderedDict)

Every day I learn something new with Python and it makes me like the language more and more.  It still has some idiosyncrasies that are annoying and I wish it played a little nicer with PostgreSQL, but it’s definitely very powerful for data science.


2 thoughts on “In Praise of Order

  1. Pingback: You going to enumerate that? | Datapolitan

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s