【问题标题】:Order/Sort a dictionary of dictionaries by a value of the sub-dictionary按子字典的值对字典字典进行排序/排序
【发布时间】:2021-05-01 10:13:40
【问题描述】:

我有一本字典,其中的值也是字典。我想按值字典的值(在示例中按日期)对主字典的键/值进行排序。

例子:

a = {
    1: {'Text': 'Test1', 'Date': '2021-05-11'},
    2: {'Text': 'Test2', 'Date': '2021-12-12'},
    3: {'Text': 'Test3', 'Date': '2021-01-01'}
    }

有序对象应如下所示:

a = {
    3: {'Text': 'Test3', 'Date': '2021-01-01'},
    1: {'Text': 'Test1', 'Date': '2021-05-11'},
    2: {'Text': 'Test2', 'Date': '2021-12-12'}
    }

我设法用字典列表做到了这一点:

a = [
    {'ID': 1, 'Text': 'Test1', 'Date': '2021-05-11'},
    {'ID': 2, 'Text': 'Test2', 'Date': '2021-12-12'},
    {'ID': 3, 'Text': 'Test3', 'Date': '2021-01-01'},
    ]

a = sorted(a, key=lambda k: k['Date'])

但我无法用字典来弄清楚。也许有人可以指出我正确的方向。

提前致谢。 弗兰克

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您需要使用a.items(),然后将密钥用作key=lambda x:x[1]['Date']x 的第二个元素是值。

    >>> a
    {1: {'Text': 'Test1', 'Date': '2021-05-11'}, 2: {'Text': 'Test2', 'Date': '2021-12-12'}, 3: {'Text': 'Test3', 'Date': '2021-01-01'}}
    >>> dict(sorted(a.items(), key=lambda x:x[1]['Date']))
    {3: {'Text': 'Test3', 'Date': '2021-01-01'}, 1: {'Text': 'Test1', 'Date': '2021-05-11'}, 2: {'Text': 'Test2', 'Date': '2021-12-12'}}
    

    【讨论】:

    • 天哪。我昨天整个晚上都坐在这个上面。非常感谢。这解决了我的问题。我会将问题标记为已解决,但我必须等待 9 分钟 :-)
    • 很高兴为您提供帮助 :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多