March 13, 2008

Python Decorate Sort Undecorate Pattern

Filed under: dev, one-liner, python — michaelangela @ 2:13 am

How do you srt a dict of items in one line?

Pythoneer » A functional task, I am sure

d = {4: 6, 12: 4, 14: 14, 18: 16, 32: 6,
33: 24, 40: 27, 41: 6, 44: 25, 106: 2}
sorted(d.items(), key=itemgetter(1))

You can also do something similar for strings of text:

Python DSU sorting idiom » STRAY neuron

words = “This is a test string from Andrew.”.split()
sorted(words, key=str.lower) [’a', ‘Andrew.’, ‘from’, ‘is’, ’string’, ‘test’, ‘This’]

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: