开发者

Pythonic way to sort list of objects by a dict value (by key) contained within the object

开发者 https://www.devze.com 2022-12-17 17:55 出处:网络
I\'m seeking advice on doing the following in a more pythonic way. Consider: class MyObj(object): def __init__(self):

I'm seeking advice on doing the following in a more pythonic way.

Consider:

class MyObj(object):
    def __init__(self):
        self.dict_properties = {}

Suppose I've got a list which contains multiple MyObj instances:

mylist = [<__main__.MyObj object at 0x1005e3b90, ...]

Now i want to sort mylist 开发者_JAVA技巧based on the value of a certain key in dict_properties in MyObj.

What does work is:

mylist.sort(lambda x,y: cmp(x.dict_properties['mykey'],
                            y.dict_properties['mykey']))

but that hardly feels pythonic.

Is there a better way (perhaps using operator.attrgetter)?


mylist.sort(key=lambda x: x.dict_properties['mykey'])

is way simpler, and faster. You could reach for operator and try to compose an attrgetter and an itemgetter, but a straightforward lambda (or def) seems simplest here.


I'd just do:

mylist.sort(key=lambda o: o.dict_properties["kykey"])

You could also overide cmp on the class.


If speed is an issue, then use decorate-sort-undecorate:

    mylist_decorated = [(elem.dict_properties['mykey'], elem) for elem in mylist]
    mylist_decorated.sort()
    mylist = [elem[1] for elem in mylist_decorated] # or zip(*mylist_decorated)[1] :)
  • this way sort() can spread its wings.
0

精彩评论

暂无评论...
验证码 换一张
取 消