按键对字典排序不再显示值

时间:2018-06-02 22:58:53

标签: python django

我有这本词典:

analytics = {
   datetime.datetime(2018, 4, 1, 0, 0):{
        'clicks': 5049,
        'month': datetime.datetime(2018, 4, 1, 0, 0)
   },
   datetime.datetime(2018, 3, 1, 0, 0): {
        'clicks': 592, 
        'month': datetime.datetime(2018, 3, 1, 0, 0)
   },
   datetime.datetime(2018, 6, 1, 0, 0): {
        'impressions': 2159, 'clicks': 223,
        'month': datetime.datetime(2018, 6, 1, 0, 0)
   },
   datetime.datetime(2018, 5, 1, 0, 0): {
        'impressions': 32747, 
        'clicks': 4184, 
        'month': datetime.datetime(2018, 5, 1, 0, 0)
   }
}

我想按日期排序,我使用它:

analytics = sorted(analytics, key=lambda k: k)

但是,虽然这会对字典进行排序,但它会删除除键之外的所有内容。知道为什么以及如何解决它?

3 个答案:

答案 0 :(得分:2)

字典无法订购。当您在字典上调用sorted时,它会将其视为可迭代的,仅由密钥生成。你可以用以下方法测试:

for k in some_dict:
    print(k)  # should produce each key

您想要的是排序dict.items,它仍然不是字典,而是更像(key, value)元组的列表

analytics = sorted(analytics.items(), key=lambda kv: kv[0])

答案 1 :(得分:2)

字典是从3.6(实现细节)开始订购的,并且由于规格为3.7,所以你可以这样做:

>>> {k: analytics[k] for k in sorted(analytics)}
{datetime.datetime(2018, 3, 1, 0, 0): {'clicks': 592, 'month': datetime.datetime(2018, 3, 1, 0, 0)}, datetime.datetime(2018, 4, 1, 0, 0): {'clicks': 5049, 'month': datetime.datetime(2018, 4, 1, 0, 0)}, datetime.datetime(2018, 5, 1, 0, 0): {'impressions': 32747, 'clicks': 4184, 'month': datetime.datetime(2018, 5, 1, 0, 0)}, datetime.datetime(2018, 6, 1, 0, 0): {'impressions': 2159, 'clicks': 223, 'month': datetime.datetime(2018, 6, 1, 0, 0)}}

答案 2 :(得分:0)

而不是dict你应该使用OrderedDict

|                                                                      VALUE |
|----------------------------------------------------------------------------|
| I always let my cat and dog at the animal nursery when I go to work by car |

请参阅文档:https://docs.python.org/2/library/collections.html#collections.OrderedDict