Editing DS4UX (Spring 2016)/Day 3 lecture

From CommunityData

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.

Latest revision Your text
Line 338: Line 338:
  Alice is the key for chocolate
  Alice is the key for chocolate
  chocolate is the value for Alice
  chocolate is the value for Alice
==== Sorting dictionaries with <code>operator</code> and <code>itemgetter</code> ====
We've already learned how you can use <code>.sorted()</code> to create a sorted version of a list. <code>.sorted()</code> accepts an optional <code>key</code> argument to tell it what to sort on. You can use <code>.sorted()</code> with <code>.items()</code> builtin dictionary function and the <code>itemgetter</code> function of the <code>operator</code> module to create sorted versions of dictionaries!
>>> import operator
>>> family = {'ozy':2, 'jonathan':34, 'portia':10, 'eva':6, 'dana':28}
>>> sorted(family.items(), key=operator.itemgetter(1), reverse=True)
[('jonathan', 34), ('dana', 28), ('portia', 10), ('eva', 6), ('ozy', 2)]
You can also use this approach to sort other complex data structures:
>>> family = [['ozy',2], ['portia',10], ['jonathan',34], ['dana', 28], ['eva', 6]]
>>> sorted(family, key=operator.itemgetter(1))
[['ozy', 2], ['eva', 6], ['portia', 10], ['dana', 28], ['jonathan', 34]]
>>> sorted(family, key=operator.itemgetter(0), reverse=True)
[['portia', 10], ['ozy', 2], ['jonathan', 34], ['eva', 6], ['dana', 28]]


== Exercise ==
== Exercise ==
<big>'''[http://jtmorgan.net/ds4ux/week3/notifications.zip Click here to download the scripts for this week's in-class exercise]'''</big>
<big>'''[http://jtmorgan.net/ds4ux/week3/notifications.zip Click here to download the scripts for this week's in-class exercise]'''</big>
Please note that all contributions to CommunityData are considered to be released under the Attribution-Share Alike 3.0 Unported (see CommunityData:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!

To protect the wiki against automated edit spam, we kindly ask you to solve the following CAPTCHA:

Cancel Editing help (opens in new window)