Skip to content

Instantly share code, notes, and snippets.

@svalleru
Created October 16, 2015 19:38
Show Gist options
  • Save svalleru/629235935b4672f9d078 to your computer and use it in GitHub Desktop.
Save svalleru/629235935b4672f9d078 to your computer and use it in GitHub Desktop.
# sorts a dictionary based on value
from collections import OrderedDict
from random import choice, randint
import string
# generate random upper case string of given length
def generateRandomString(len):
return ''.join(choice(string.ascii_uppercase + string.digits) for _ in range(len))
#create a dict with arbitrary K-Vs
my_dict = {}
for i in xrange(30):
my_dict[generateRandomString(2)] = randint(0, 100) # generateRandomString(4)
# print out the original arbitrary dict
print '#'*10+'UNSORTED'+'#'*10
for k, v in my_dict.iteritems():
print k, v
# print out the sorted dict
print '#'*10+'SORTED'+'#'*10
for k, v in OrderedDict(sorted(my_dict.items(), key=lambda x:x[1], reverse=True)).iteritems():
print k, v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment