Understanding dictionary.get in Python
<p>I was reading this really helpful SO post on <a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">sorting dictionaries</a>. One of the most popular answers suggests this:</p>

<pre><code>sorted(dict1, key=dict1.get)
</code></pre>

<p>While this seems to work perfectly fine, I don't get the <code>key=dict1.get</code> part. </p>

<p>What exactly is <code>get</code> here and what does it do? </p>

<p>I am only familiar with using <code>get('X')</code> to extract X from a dictionary...
And I couldn't find anything in the <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow">docs</a> on dictionaries and stdtypes, so any pointers are much appreciated!</p>

<p>NB here is what <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow">they</a> have to say about <code>get()</code>, or is this something entirely different?
Thanks!</p>

<blockquote>
  <p>get(key[, default])
  Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError</p>
</blockquote>

<p>As you have found, <code>get</code> just gets the value corresponding to a given key. <code>sorted</code> will iterate through the iterable it's passed. In this case that iterable is a <code>dict</code>, and iterating through a <code>dict</code> just iterates through its keys. If you want to sort based on the values instead, you need to transform the keys to their corresponding values, and of course the obvious way to do this is with <code>get</code>.</p>

<p>To clarify, this is for if you want a list of keys sorted based on their values. If you just wanted a sorted list of values you could do <code>sorted(dict1.values())</code>, and if you wanted the keys sorted by their value (not the value they map to), you could just do <code>sorted(dict1)</code>.</p>

<p>Example:</p>

<pre><code>&gt;&gt;&gt; d = {'a': 3, 'b': 2, 'c': 1}
&gt;&gt;&gt; sorted(d)
['a', 'b', 'c']
&gt;&gt;&gt; sorted(d.values())
[1, 2, 3]
&gt;&gt;&gt; sorted(d, key=d.get)
['c', 'b', 'a']
</code></pre>

python dictionary