Re: Sorting dictionary by datetime value

Discussion in 'Python' started by Chris Angelico, Feb 8, 2014.

  1. On Sat, Feb 8, 2014 at 6:06 PM, Igor Korot <> wrote:
    >>>> sorted(a.items(), key=a.get)

    > [('1', datetime.datetime(2012, 12, 28, 12, 15, 30, 100)), ('3', datetime.datetim
    > e(2012, 12, 28, 12, 16, 44, 100)), ('2', datetime.datetime(2012, 12, 28, 12, 17,
    > 29, 100))]
    >>>>

    >
    > However, trying to do the same thing from the script does not sort the
    > dictionary:
    >
    > sorted(my_dict.items(), key=my_dict.get, reverse=False)
    > for key, value in my_dict.items():
    > print value, key
    >
    > the dictionary prints with unsorted items.


    The sorted() function returns a sorted list. You're then going back to
    the original dictionary. Instead, just iterate over the sorted items:

    items = sorted(my_dict.items(), key=my_dict.get, reverse=False)
    for key, value in items:
    print value, key

    ChrisA
     
    Chris Angelico, Feb 8, 2014
    #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. Christos TZOTZIOY Georgiou
    Replies:
    3
    Views:
    734
    Christos TZOTZIOY Georgiou
    Sep 13, 2003
  2. Tim Peters
    Replies:
    0
    Views:
    556
    Tim Peters
    Sep 9, 2003
  3. mp
    Replies:
    1
    Views:
    403
    John Machin
    Jul 28, 2006
  4. Martin
    Replies:
    0
    Views:
    350
    Martin
    Dec 27, 2008
  5. Igor Korot

    Sorting dictionary by datetime value

    Igor Korot, Feb 8, 2014, in forum: Python
    Replies:
    0
    Views:
    77
    Igor Korot
    Feb 8, 2014
Loading...

Share This Page