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>The <code>key</code> argument to <code>sorted</code> is a <em>callable</em> (e.g. a function) which takes one argument.</p>

<p>By default, <code>sorted</code> sorts the values by comparing them to each other. For example:</p>

<pre><code>sorted([2, 3, 1])   # returns [1, 2, 3]
</code></pre>

<p>This is because 1 &lt; 2 &lt; 3.</p>

<p>On the other hand, if a different value should be used for comparison, that can be defined with <code>key</code>. For example, to sort strings by length, one coudld do:</p>

<pre><code>def string_length(s):
    return len(s)

sorted(['abcd', 'efghi', 'jk'], key=string_length)  # returns ['jk', 'abcd', 'efghi']
</code></pre>

<p>This is because <code>string_length('jk') &lt; string_length('abcd') &lt; string_length('efghi')</code>.</p>

<p>But instead of a funcion, you can pass any other <em>callable</em>. In your example, that is <code>dict1.get</code>, so for each key in the dict, <code>dict1.get(key)</code> will be executed and the result of that will be used in comparison.</p>

<pre><code>dict1 = {'a':3, 'b':1, 'c':2}

sorted(dict1, key=dict1.get) # returns ['b', 'c', 'a']
</code></pre>

<p>This is because <code>dict1.get('b') &lt; dict1.get('c') &lt; dict1.get('a')</code>.</p>

python dictionary