How can i sort this dict per datetime?
How can i sort this dict per datetime? Is it possible?
{
1: {'l':{'created_on': datetime.datetime(2011, 9, 29, 17,开发者_StackOverflow社区 39, 26)}},
2: {'l':{'created_on': datetime.datetime(2011, 9, 23, 17, 39, 26)}},
3: {'l':{'created_on': datetime.datetime(2011, 9, 30, 17, 39, 26)}}
}
You can call the sorted() function on the values, with the datetime as the comparison key:
sorted(d.values(), key=lambda item: item["l"]["created_on"])
You can get a sorted list of keys for your dictionary d
(dictionaries cannot be sorted by themselves):
>>> sorted(d.keys(), key=lambda k: d[k]['l']['created_on'])
[2, 1, 3]
PS: If you really need a dictionary with sorted keys, the now standard OrderedDict type is your friend (as described in the comments by rocksportrocker and agf after Frédéric's answer).
You can not sort a dict() itself. The dict has no implict order:
>>> print dict(a=3, b=2, c=1)
{'a': 3, 'c': 1, 'b': 2}
If you want to keep the full structure of your dict, you have to flatten your dict dd
into a list li
first. Then you can sort with the datetime
value as a key:
import operator
dd = { 1: ..... }
li = []
for (i, it) in dd.items():
for (l, it1) in it.items():
for (c, dt) in it.items():
li.append((i, l, c, dt))
li.sort(key=operator.itemgetter(3))
print li
精彩评论