对值为Python对象的Dict进行排序

时间:2015-05-05 03:31:51

标签: python list sorting object sorted

我有一个dict,其值为list s的Object

我需要根据对象的一个​​属性对它们进行排序。

{key1 : [(list1 of obj),(list2 of obj),(list3 of obj)], key2 : [(list1 of obj),(list2 of obj)]}

我需要按其中一个属性对list个值进行排序,例如: "数量"

我的代码结构是:

for objlist in mydict[key]:
    sorted(objlist ,key=lambda k: (k.Quantity),reverse=True)
    sorted(objlist , key=operator.itemgetter)
    s = sorted(s, key = lambda x: (x[1], x[2]))
    objlist.sort(key=operator.attrgetter("Quantity"), reverse=False)
    objlist.sort(key = lambda x: x.Quantity)

我尝试了以上所有选项但没有任何效果。

2 个答案:

答案 0 :(得分:1)

以下是一些示例代码

class Test():
    def __init__(self,q):
        self.Quantity = q
    def __repr__(self):
        return "<Class Test: Quantity=" + str(self.Quantity) + ">"
mydict = mydict = {"a":[ Test(3), Test(2), Test(4)], "b": [Test(8), Test(10), Test(6)], "c":[Test(14), Test(12), Test(20)]}
print "Before Sort"
for key in mydict:
    print (key,mydict[key])


dict_with_sorted_list = {}
for key in mydict:
    dict_with_sorted_list[key] = sorted(mydict[key], key=lambda k: k.Quantity, reverse=True)
print "After Sort"
for key in dict_with_sorted_list:
    print (key,dict_with_sorted_list[key])

答案 1 :(得分:0)

如果您只是将已排序的列表分配回原始字典,您还可以使用列表对象的sort()方法对每个列表进行排序,并避免创建新列表。用法类似于sorted()。由于您未创建新列表,sort()方法比使用sorted()更快。在实践中,它通常不会产生太大的影响,除非你发现需要优化,这是一个关键点。

>>> # Python 3.x
... from random import randint
>>>
>>> class Test(object):
...     # Borrowed from the accepted answer.
...     def __init__(self, q):
...         self.Quantity = q
...     def __repr__(self):
...         return "<Class Test: Quantity=%d>" % self.Quantity
...
>>> keys = 'a b c'.split()
>>> my_dict = {key: [Test(randint(0, 50)) for _ in range(3)] for key in keys}
>>> print("Before sorting:")
Before sorting:
>>> for key in keys:
...     print("%s" % my_dict[key])
...
[<Class Test: Quantity=13>, <Class Test: Quantity=49>, <Class Test: Quantity=9>]
[<Class Test: Quantity=30>, <Class Test: Quantity=3>, <Class Test: Quantity=6>]
[<Class Test: Quantity=29>, <Class Test: Quantity=33>, <Class Test: Quantity=37>]
>>> for key in keys:
...     my_dict[key].sort(key=lambda k: k.Quantity, reverse=True)
...
>>> print("After sorting:")
After sorting:
>>> for key in keys:
...     print("%s" % my_dict[key])
...
[<Class Test: Quantity=49>, <Class Test: Quantity=13>, <Class Test: Quantity=9>]
[<Class Test: Quantity=30>, <Class Test: Quantity=6>, <Class Test: Quantity=3>]
[<Class Test: Quantity=37>, <Class Test: Quantity=33>, <Class Test: Quantity=29>]
>>>