user2294401
user2294401

Reputation: 387

How can i sort the list with keys in python

I have the two list dictionary like this

obj1 = [mydict['obj1'],mydict['obj2'],mydict['obj3'],mydict['obj4']]  
obj2 = [mydict['obj1'],mydict['obj2'],mydict['obj3'],mydict['obj4'], mydict['obj5'] ] 

Now i want that

  1. Count the number of elements in each list
  2. Then based on whichever is greater then get that list of objects

I want a single list which conatins the above two list of(list of) dictionaries based on the higher number of elements so that i cause something like this

mylist = myfunc(objects1, objects2  )

mylist should be a list like [objects1, objects2] depending upon who has greater number of objects.

what is the best way to do that with less lines of code

Something like EDIT

mylist = sorted([obj1, obj2], key=lambda a: len(a), reverse=True)

Upvotes: 0

Views: 78

Answers (2)

Yoriz
Yoriz

Reputation: 3625

objects1 = [1, 2, 3]
objects2 = ['1', '2', '3', '4']

mylist = [objects1, objects2]
mylist.sort(key=len, reverse=True)
print mylist

[['1', '2', '3', '4'], [1, 2, 3]]

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304147

There's no need to use a lambda function if it's just going to call a function anyway.

>>> objects1 = [1, 2, 3]
>>> objects2 = ['1', '2', '3', '4']
>>> 
>>> mylist = [objects1, objects2]
>>> max(mylist, key=len)
['1', '2', '3', '4']

>>> sorted(mylist, key=len, reverse=True)
[['1', '2', '3', '4'], [1, 2, 3]]

Upvotes: 2

Related Questions