Reputation: 19
I have sorted a dictionary based on a value within that dictionary. Now, I want to print ordered, relevant aspects of the dictionary, using the sorted list of keys.
Here's what I tried so far:
sc = sorted(stats,key=lambda x:(stats[x]['avg length'],x)) #to get a sorted list of keys
for sc in stats:
print "Name %s, Number: %s, Average length: %s, Max length: %s, Min length: %s" % (sc, stats[sc]["number"],stats[sc]["avg length"], stats[sc]["max length"], stats[sc]["min length"])
However, the order of the output does not match the order of my list sc. In fact, I cannot see any pattern with how the values outputted..
Sorry if this is a trivial question--I'm new to python :(
Upvotes: 0
Views: 152
Reputation: 298156
Your for
loop is a little backwards. You want to iterate over your ordered keys, not your original dictionary:
for key in sc:
print ... % (key, stats[key], ...
Upvotes: 2
Reputation: 815
At a guess, you probably meant to write something like:
for s in sc:
print "Name %s, Number: %s, Average length: %s, Max length: %s, Min length: %s" % (s, stats[s]["number"],stats[s]["avg length"], stats[s]["max length"], stats[s]["min length"])
You're replacing the sorted list in the existing for loop assignment.
Upvotes: 2