In Python, how can you easily retrieve sorted items from a dictionary?
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p>

<p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p>

<p>For example, you had this:</p>

<pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
</code></pre>

<p>I want to print the associated values in the following sequence sorted by key:</p>

<pre><code>this is a
this is b
this is c
</code></pre>

<p>Do you mean that you need the values sorted by the value of the key?
In that case, this should do it:</p>

<pre><code>for key in sorted(d):
    print d[key]
</code></pre>

<p><strong>EDIT:</strong> changed to use sorted(d) instead of sorted(d.keys()), thanks <a href="http://stackoverflow.com/users/1694/eli-courtwright" rel="nofollow">Eli</a>!</p>
