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>

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

<p>is a less verbose and more pythonic way of saying:</p>

<pre><code>sorted(dict1, key=lambda x: dict1[x] if x in dict1 else None)
</code></pre>

<p>Bear in mind that iterating on a dictionary will return its keys, therefore the <code>get</code> method takes arguments which are the dictionary keys, which in turn returns the value that key is pointing to. </p>

<p>TL;DR It's a simple way of saying sort the dictionary keys using the values as the sort criteria.</p>

python dictionary