[英]Sorting a Dict whose values are objects Python
I have a dict
in which the values are list
s of Object
s. 我有一个dict
,其中的值是Object
的list
。
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, eg "Quantity". 我需要按属性之一对值list
进行排序,例如“数量”。
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. 我尝试了上述所有选项,但没有任何效果。
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])
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. 如果您只是将排序后的列表分配回原始词典,则还可以使用列表对象的sort()
方法对每个列表进行排序,并避免创建新列表。 The usage is similar to sorted()
. 用法类似于sorted()
。 Because you're not creating a new list, the sort()
method is a hair faster than using sorted()
. 因为您没有创建新列表,所以sort()
方法比使用sorted()
更快。 In practice, it won't generally make much difference, unless you find a need to optimize and this is a pinch point. 在实践中,除非您发现需要优化,否则这通常不会有太大变化,这是一个紧要关头。
>>> # 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>]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.