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

时间:2022-05-24 07:42:29

I have a dict in which the values are lists of Objects.

我有一个dict,其值是对象列表。

I need to sort them based on one of the object's attributes.

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

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

I need to sort the list of values by one of the attributes, e.g. "Quantity".

我需要通过其中一个属性对值列表进行排序,例如“数量”。

My code structure is:

我的代码结构是:

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)

I tried all the above options but nothing worked.

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

2 个解决方案

#1


Here is some sample code for you

以下是一些示例代码

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])

#2


If you're simply assigning the sorted lists back to the original dictionary, you can also use the list object's sort() method to sort each list in place and avoid creating a new list. The usage is similar to sorted(). Because you're not creating a new list, the sort() method is a hair faster than using sorted(). In practice, it won't generally make much difference, unless you find a need to optimize and this is a pinch point.

如果您只是将已排序的列表分配回原始字典,您还可以使用列表对象的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>]
>>>    

#1


Here is some sample code for you

以下是一些示例代码

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])

#2


If you're simply assigning the sorted lists back to the original dictionary, you can also use the list object's sort() method to sort each list in place and avoid creating a new list. The usage is similar to sorted(). Because you're not creating a new list, the sort() method is a hair faster than using sorted(). In practice, it won't generally make much difference, unless you find a need to optimize and this is a pinch point.

如果您只是将已排序的列表分配回原始字典,您还可以使用列表对象的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>]
>>>    

相关文章