2

I have a dictionary and I want to sort it according to its key. Although I dont have an error, my key value (date) is not sorted.

If anyone could help me, I will be happy. Thanks.

    d = defaultdict(list)

    for row in rows:
        date = row[0]
        speed = float(row[1])

        if date not in d:
            d[date] = [speed]
        elif date in d:
            speeds = d[date]
            speeds.append(speed)
            d[date] = speeds

        date = d.keys()
        date = sorted(d,key=lambda key:d[key])

        print date

"Print date" result:

['2015/01/01 10:04', '2015/01/01 08:40', '2015/01/01 10:14', '2015/01/01 09:56', '2015/01/01 09:54', '2015/01/01 10:08', '2015/01/01 10:06', '2015/01/01 10:10', '2015/01/01 10:16', '2015/01/01 09:52']
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
serenade
  • 359
  • 2
  • 5
  • 13
  • 6
    Possible duplicate of [How can I sort a dictionary by key?](http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – midori Feb 03 '16 at 17:25
  • No, I have used all these recommended algorithm but I have a non sorted result at the end. @minitoto – serenade Feb 03 '16 at 17:42
  • 2
    Regular python dictionaries have no order in python. use ordered dictionary. https://docs.python.org/2/library/collections.html#collections.OrderedDict – BrockLee Feb 03 '16 at 17:52

1 Answers1

0

I believe changing

date = d.keys()

to

date = sorted( d.keys() )

and removing

date = sorted(d,key=lambda key:d[key])

should work? I think the above line sorts by the contents in d[key] and not by key. If not, sorting by datetime objects should work as well:

import datetime
dates = sorted( [datetime.datetime.strptime(i,"%Y/%m/%d %H:%M") for i in d.keys()] )

# to access dictionary values in order:
for date in dates:
    entry = d[ date.strftime("%Y/%m/%d %H:%M") ]
Lucas Currah
  • 418
  • 4
  • 8