# # this sorts a dictionary in a variety of ways # d = { "hello" : 2, "Goodbye" : 69, "gleep" : 21, "Howdy": -3 } d["snork"] = -36 # # first, just print it as stored # print("Dictionary entries, as stored:") n = 1 for i in d: print("%d. key: '%s' --> value: '%d'" % (n, i, d[i])) n += 1 # # now, sort them by key # print("\nDictionary entries, sorted by key:") klist = d.keys() n = 1 for i in sorted(klist): print("%d. key: '%s' --> value: '%d'" % (n, i, d[i])) n += 1 # # same thing, but collapse the case # print("\nDictionary entries, sorted by key with collapsed case:") klist = d.keys() n = 1 for i in sorted(klist, key=str.lower): print("%d. key: '%s' --> value: '%d'" % (n, i, d[i])) n += 1 # # sort them by key, but done by looking at the first element of # each pair in the dictionary # print("\nDictionary entries, sorted by key in a different way:") ilist = d.items() n = 1 for i in sorted(ilist, key=lambda x: x[0]): print("%d. key: '%s' --> value: '%d'" % (n, i[0], i[1])) n += 1 # # same thing, but collapse the case # print("\nDictionary entries, sorted by key with collapsed case in a different way:") ilist = d.items() n = 1 for i in sorted(ilist, key=lambda x: x[0].lower()): print("%d. key: '%s' --> value: '%d'" % (n, i[0], i[1])) n += 1 # # now sort by increasing value # print("\nDictionary entries, sorted by (increasing) value:") ilist = d.items() n = 1 for i in sorted(ilist, key=lambda x: x[1]): print("%d. key: '%s' --> value: '%d'" % (n, i[0], i[1])) n += 1 # # now sort by decreasing value # print("\nDictionary entries, sorted by (decreasing) value:") ilist = d.items() n = 1 for i in sorted(ilist, key=lambda x: -x[1]): print("%d. key: '%s' --> value: '%d'" % (n, i[0], i[1])) n += 1 # # fun sort: by the fourth power of th value (this will put 2 before -3) # print("\nDictionary entries, sorted by the fourth power of the value:") ilist = d.items() n = 1 for i in sorted(ilist, key=lambda x: x[1]**4): print("%d. key: '%s' --> value: '%d'" % (n, i[0], i[1])) n += 1 # # sort by the reverse of each key # def revstr(x): return x[::-1] print("\nDictionary entries, sorted by the reverse of the key:") klist = d.keys() n = 1 for i in sorted(klist, key=lambda x: revstr(x)): print("%d. key: '%s' --> value: '%d'" % (n, i, d[i])) n += 1 # # sort by the reverse of each key; this time, it's using items # print("\nDictionary entries, sorted by the reverse of the key using items:") ilist = d.items() n = 1 for i in sorted(ilist, key=lambda x: revstr(x[0])): print("%d. key: '%s' --> value: '%d'" % (n, i[0], i[1])) n += 1