Reputation: 192346
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
Upvotes: 12
Views: 1352
Reputation: 30609
This snippet will do it. If you're going to do it frequently, you might want to make a 'sortkeys' method 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()
.
Upvotes: 2
Reputation: 618
Do you mean "sorted" instead of "ordered"? It seems your question aims at sorting a dictionary and not at ordering it. If you do mean "ordered", you can use an OrderedDict from the collections module. Those dictionaries remember the order in which the key/value pairs were entered:
from collections import OrderedDict
Reference information: https://docs.python.org/2/library/collections.html#collections.OrderedDict
Upvotes: 0
Reputation: 2287
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
Upvotes: 2
Reputation: 75805
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!
Upvotes: 17
Reputation: 71023
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
Upvotes: 0
Reputation: 122940
>>> 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
Upvotes: 0
Reputation: 993951
Or shorter,
for key, value in sorted(d.items()):
print value
Upvotes: 16