Adjust sorting of dictionary keys etc for Python 3.

On Python 2 my_dict.keys() is a list so has a .sort() method.
On Python 3 my_dict.keys() is an iterator so use sorted() function.
Fix some print statements/functions to work on both Python 2 & 3