views:

612

answers:

7

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.

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

For example, you had this:

d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}

I want to print the associated values in the following sequence sorted by key:

this is a
this is b
this is c
+1  A: 

This snippet will do so. If you're going to do it frequently, you might want to make a 'sortkeys' method or somesuch to make it easier on the eyes.

keys = list(d.keys())
keys.sort()
for key in keys:
    print d[key]

Edit: dF's solution is better -- I forgot all about sorted().

Cody Brocious
Yes, but sorted isn't available in older python (pre 2.4), so this idiom is still useful.
jmanning2k
+15  A: 

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

for key in sorted(d):
    print d[key]

EDIT: changed to use sorted(d) instead of sorted(d.keys()), thanks Eli!

dF
You can actually just say "for key in sorted(d):" without having to say "d.keys()" since iterating over a dictionary just iterates over its keys.
Eli Courtwright
+14  A: 

Or shorter,

for key, value in sorted(d.items()):
    print value
Greg Hewgill
not just sorted - avoids the lookups
Blair Conrad
what exactly do you mean by "avoids the lookups"? does it result in better performance?
Ray Vega
@Ray: yes, using "key, value" in the for loop avoids having to do the hash table lookup of d[key] for every item in the dictionary. I believe the above solution will be faster, but you'd have to measure it on your system and data set to be sure.
Greg Hewgill
+1  A: 
>>> d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
>>> for k,v in sorted(d.items()):
...     print v, k
... 
this is a a
this is b b
this is c c
Aaron Maenpaa
A: 
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
ks = d.keys()
ks.sort()
for k in ks:
    print "this is " + k
Frank Krueger
+1  A: 
for key in sorted(d):
  print d[key]
Will Boyce
A: 

You can also sort a dictionary by value and control the sort order:

import operator

d = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}

for key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):
    print key, " ", value

Output:
b this is 3
a this is 2
c this is 1

Cookey