Re: Sort dictionary by value when value is a list

Discussion in 'Python' started by Chris Rebert, Nov 14, 2008.

  1. Chris Rebert

    Chris Rebert Guest

    On Fri, Nov 14, 2008 at 10:26 AM, major-john <> wrote:
    > I'm having trouble sorting a dictionary based on values when the values are
    > all lists, and i want to sort the list by key with the largest value lists
    > in decreasing size.
    >
    > Currently, I have the following:
    >
    > from operator import itemgetter
    >
    > dict = {'A': [(10, 20), (12, 18), (5, 11), (18, 25)], 'C': [(1, 200)], 'B':
    > [(1, 10), (100, 200), (150, 300), (250, 350), (300, 400)], 'D': [(3, 400)]}
    >
    > I have tried several methods, and seem to have come closest using:
    >
    > sorted(self.dict.items(), key=itemgetter(1), reverse=True)
    >
    > My problem is that this will return the key order A,D,C,B
    > The order I want is based on the size of the lists each key points to:
    > B,A,D,C or B,A,C,D
    >
    > Question:
    > itemgetter(1) is just returning the value, which is a list. How do I
    > specify that I want the values to be sorted by list size?


    You just need to add a call to len() in the key function:

    sorted(self.dict.items(), key=lambda pair: len(pair[1]), reverse=True)

    Cheers,
    Chris
    --
    Follow the path of the Iguana...
    http://rebertia.com

    >
    > Thanks!
    > john
    >
    >
    >
    >
    >
    > --
    > "We are healthy only to the extent that our ideas are humane." --Killgore
    > Trout
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    >
     
    Chris Rebert, Nov 14, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ilias Lazaridis
    Replies:
    6
    Views:
    455
    Ilias Lazaridis
    Feb 21, 2006
  2. james_027
    Replies:
    1
    Views:
    338
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  3. Replies:
    7
    Views:
    756
    Stefan Arentz
    Sep 10, 2007
  4. Navkirat Singh
    Replies:
    6
    Views:
    3,165
    Navkirat Singh
    Jul 29, 2010
  5. Navin
    Replies:
    1
    Views:
    729
    Ken Schaefer
    Sep 9, 2003
Loading...

Share This Page