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.
Dicts don’t have a reliable order.
You can use an
OrderedDictinstead.See it working online: ideone
Note that the
OrderedDictorders according to insertion order, not by key order. The above code inserts items into theOrderedDictin 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.