2

I have a dictinary like below and trying to sort that by keys(which are date time object):

def t(date_st):
    return datetime.strptime(date_st, '%d-%m-%Y')

def sort_dict_data(data):
keylist = data.keys()
keylist.sort()
sorted_x = {}
for key in keylist:
    sorted_x.update({datetime.strftime(key, '%d-%m-%Y'):data.get(key)})
return sorted_x



print sort_dict_data({t('07-07-2012'): 3.5, t('09-07-2012'): 9.0, t('08-07-2012'): 5.0})
results: {'07-07-2012': 3.5, '09-07-2012': 9.0, '08-07-2012': 5.0}

How I can get that like:

{'07-07-2012': 3.5, '08-07-2012': 5.0, '09-07-2012': 9.0}

Thanks in advance.

  • Dictionaries are unordered. You can sort the keys and store them in an array, but putting them back in the dict won't make the dict sorted. – jordanm Aug 10 '12 at 20:21

2 Answers2

3

Dicts don't have a reliable order.

You can use an OrderedDict instead.

def sort_dict_data(data):
    return OrderedDict((datetime.strftime(k, '%d-%m-%Y'), v)
                       for k, v in sorted(data.iteritems()))

See it working online: ideone

Note that the OrderedDict orders according to insertion order, not by key order. The above code inserts items into the OrderedDict in key order, giving you the result you want. But it is important to remember that any later additions you make to the dictionary will appear at the end, not in the correct position according to key order.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

OrderedDict preserves order of insertion (the chronology), not key order. Plain dict's don't preserve either.

For dictionaries sorted by keys, you likely want a Treap, Red-Black tree, or one of the many other tree datastructures known to computer science.

Treaps are fast on average, but will be a bit slow once in an infrequent while, as it rebalances itself.

Red-Black trees are well known, relatively complex (compared to treaps), and give OK performance on average. Their chief benefit is that they don't have highly variable performance, making them sometimes-nice in user interfaces.

I recently did a performance comparison of datastructures that are like dicts but with sorted keys. It can be found here: http://stromberg.dnsalias.org/~strombrg/python-tree-and-heap-comparison/

user1277476
  • 2,871
  • 12
  • 10