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 second parameter of <code>sorted([dictionnary],[function])</code> is a function and not a value:</p>

<p>This means the method will compare the keys according to the value returned by the function applied to the items.</p>

<p>the parenthesis added after a function call mean you are passing a value, while without the parenthesis you pass the function</p>

<p><code>dict.get(x)</code> is the value of the key x in dict </p>

<p><code>dict.get</code> is the function that gets the said value from dict1</p>

<p>supposing we have </p>

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

<p><code>sorted(d)</code> will compare 'a','b'and 'c' while <code>sorted(d,d.get)</code> will compare <code>d.get('a')</code>,<code>d.get('b')</code> and <code>d.get('c')</code></p>

python dictionary