Python's "sorted" method allows you to pass a key to it for returning the value to compare by. I'm surprised I didn't end up using this before. I had read about it in the documentation, but hadn't put it to use yet. This is best shown through a short example.
I have a list of dictionaries, the values of which are being displayed to the user in a tabular format. Some of these dictionaries have a key, 'money', which contains a string representation of a monetary value, perhaps with a currency symbol, perhaps not.
We want to display the values from the dictionaries that have the 'money' key at the top of the results list, sorted from lowest to highest. This is not a very difficult problem to begin with, but it's trivially easy in python. The solution looks something like this:
def get_results():
def by_monetary(item):
if item.has_key('money'):
value = to_decimal(item['money'])
return value
else:
return 0
...
return sorted(results, key=by_monetary)
This is going to come in really handy in the future, especially in cases where I have no control over where my data is coming from, or what format it is in. You probably already knew about this, but if you didn't, I hope you find it useful
No comments:
Post a Comment