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> |