Re: [Hampshire] Python sorting

Top Page

Reply to this message
Author: Robin Wilson
Date:  
To: Hampshire LUG Discussion List
Subject: Re: [Hampshire] Python sorting
Hi Leo,

You can do this fairly easily using the 'key' keyword argument for the 'sorted' function. Sorting a normal list can be done easily as:

s = sorted(test)

But if you want to tell it how to generate the value to sort on, you can use the key keyword, for example:

s = sorted(test, key=str.lower)

As you can see, the key parameter gives a function to be called on each of the elements before comparing them. In that case it uses a built-in Python function to convert each element to lowercase, but you can write your own function very easily to do what you want. You can do this by writing a normal function, like:

def f(value):
    return value.prop


and then calling it as follows:

s = sorted(test.itervalues(), key=f)

or by writing a lambda function, which is basically the same, but inline and without a name:

s = sorted(test.itervalues(), key=lambda x: x.prop)

I'm using test.itervalues() as the list to use here as that will just provide a list of the values in the dictionary, not the keys.

Hope that helps,

Cheers,

Robin

On 1 Sep 2012, at 15:53, Leo <linux@???> wrote:

> If I have a dictionary in Python, where the keys are strings, and the values are instances of a class of mine, how can I get the list of keys sorted based on a property on my class? I can obviously do this manually, but was wondering if there was an inbuilt Python way of doing it more easily. As an example:
>
> Class MyClass:
>     def __init__(self, prop)
>         self.prop = prop

>
> def main():
>     test=dict()
>     test["a"] = MyClass(46)
>     test["b"] = MyClass(3)
>     test["c"] = MyClass(15)

>
>     # I would like to generate
>     sortedTest=list()
>     #containing b, c, a in that order.

>
> Thanks,
> Leo
>     
>
> --
> Please post to: Hampshire@???
> Web Interface: https://mailman.lug.org.uk/mailman/listinfo/hampshire
> LUG URL: http://www.hantslug.org.uk
> --------------------------------------------------------------



--
Please post to: Hampshire@???
Web Interface: https://mailman.lug.org.uk/mailman/listinfo/hampshire
LUG URL: http://www.hantslug.org.uk
--------------------------------------------------------------