Patryk
Patryk

Reputation: 24092

How to perform custom sort in python on dictionary with custom class keys?

I need to sort a dictionary returned by pysphere's VIServer.get_datastore. It should be sorted by free space on the datastore which we can get by :

from pysphere import VIServer, VIProperty
if __name__ == "__main__":
    server = VIServer()
    print "Connecting to vSphere..."
    server.connect(VSPHERE_IP, VSPHERE_USER, VSPHERE_PASS)
    datastores = server.get_datastores()
    for ds, name in datastores.iteritems():
        props = VIProperty(server, ds)
        freeSpace = props.summary.freeSpace

I know I can use sorted(iterable[, cmp[, key[, reverse]]]) and create a custom sort function but I do not know which type will there be as an argument to this function.

I can't use OrderedDict because I am bound to python 2.6 (don't ask why :( )

Upvotes: 0

Views: 139

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121804

Just perform the lookup for free space in your key function:

server = VIServer()
server.connect(VSPHERE_IP, VSPHERE_USER, VSPHERE_PASS)
datastores = server.get_datastores()

ds_keys = sorted(datastores,
                 key=lambda ds: VIProperty(server, ds).summary.freeSpace
                 reverse=True)

This produces a sorted list of the keys from datastores; you can use that to iterate in a specific order. I presumed you wanted the datastore with the most space free listed first.

You can get sorted key-value pairs too, replace ds with item and item[0], respectively:

ds_items = sorted(datastores.items(),
                  key=lambda item: VIProperty(server, item[0]).summary.freeSpace
                  reverse=True)

Upvotes: 1

Related Questions