Sometimes we want to iterate over a dictionary in sorted order of values. We can do it by using key argument to python sorted() method and passing lambda function to it. Here is the code snippet for few scenarios:
Sort by numeric dictionary values
#!/usr/bin/python d = {"a":1, "b":5, "c":2, "be":30} for k in sorted(d.keys(), key=lambda x:d[x]): print "%s=%s" % (k, d[k])
# output is from above code is:
a=1 c=2 b=5 be=30
Sort by numeric dictionary values but treating them as strings
We’ll apply str() function to values in lambda function.
#!/usr/bin/python d = {"a":1, "b":5, "c":2, "be":30} for k in sorted(d.keys(), key=lambda x:str(d[x])): print "%s=%s" % (k, d[k])
# output is from above code is:
a=1 c=2 be=30 b=5