0

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

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.

8
  • sorted returns a new list, which you are not capturing. What is the class of Quantity? It need to be a class with the comparison operators implemented. Commented May 5, 2015 at 3:38
  • Also I need the sorted values should be a object as well. Since I will be using the attribute name Commented May 5, 2015 at 3:38
  • You are not iterating through the values, try your last one with for objlist in mydict.values() Commented May 5, 2015 at 3:40
  • I didn't get " What is the class of Quantity? It need to be a class with the comparison operators implemented". Basically my dictionary is a output of a sql query which has key and studentID and values as one complete row of the sql output. one of the column in the table is Quantity which is a attribute in that object. I need to sort using that Commented May 5, 2015 at 3:41
  • 1
    Can you give us a minimal, complete, verifiable example, including a simple type with an attribute, instead of making us try to talk around the vagueness in ways that are just going to confuse you? Commented May 5, 2015 at 3:51

2 Answers 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])
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.