python dictionaries

Copying

Python Dictionaries do not like to be copied - in fact this is an understatement.

But if you want a copy then this is how

    import copy

    def COPYIT(self):
     #This is necessary in order to copy a dictionary
     dict2 = copy.deepcopy(self.struct)
     return dict2

Sort by Value

How to sort a dict by value (Python 2.4 or greater):

for key, value in sorted(mydict.iteritems(),
     key=lambda (k,v): (v,k)):
    print "%s: %s" % (key, value)

As a List

res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))

Sort by Key

import collections
d = {2:3, 1:89, 4:5, 3:0}
od = collections.OrderedDict(sorted(d.items()))

od
OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])


for k, v in od.items(): print(k, v)

Or

keylist = mydict.keys()
keylist.sort()
for key in keylist:
    print "%s: %s" % (key, mydict[key])