<p><s>这里的想法是使用<code>OrderedDict</code>,因为<code>dictionary</code>没有排序的范围,而orderedict保留条目顺序。</s></p>
<p>这里的想法是使用<code>list of tuples of (key, value) pairs</code>,因为<code>dictionary</code>没有排序范围,而orderedict保留条目顺序。
此外,我们还必须将键转换为实际的<code>datetime</code>对象</strong>才能使排序完美工作,否则将按字母顺序对基于字符串的字段进行排序。</p>
<p><strong>代码:</strong></p>
<pre><code>from datetime import datetime
#from collections import OrderedDict
data = {
"01-01-2015" : "some data",
"05-05-2015" : "some data",
"03-04-2015" : "some data"
}
#ordered_data = OrderedDict(
# sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'), reverse=True))
#Since OP is using python 2.6 where OrderedDict is not present, I changed the solution and the original solution is commented out
ordered_data = sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'), reverse=True)
print(ordered_data)
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>[('05-05-2015', 'some data'), ('03-04-2015', 'some data'),
('01-01-2015', 'some data')]
</code></pre>
<p><strong>说明:</strong>(用于将键转换为日期时间进行排序)</p>
<p>如果将日期字段保留为字符串,则会考虑字典顺序,并且<code>3</code>在<code>0</code>之后,因此<code>a>b</code>是<code>True</code>,但它们的日期对应项不是这样。<code>Feb</code>肯定在<code>Jan</code>之后。</p>
<pre><code>a = "30-01-2015"
b = "01-02-2015"
print(a>b) #True
a_datetime = datetime.strptime(a, '%d-%m-%Y')
b_datetime = datetime.strptime(b, '%d-%m-%Y')
print(a_datetime>b_datetime) #False
</code></pre>