[英]Order/Sort a dictionary of dictionaries by a value of the sub-dictionary
I have a dictionary where the values are dictionaries too.我有一本字典,其中的值也是字典。 I want to order the key/values of the main dictionary by a value of the value-dictionaries (in the example by date).
我想通过值字典的值(在示例中按日期)对主字典的键/值进行排序。
Example:例子:
a = {
1: {'Text': 'Test1', 'Date': '2021-05-11'},
2: {'Text': 'Test2', 'Date': '2021-12-12'},
3: {'Text': 'Test3', 'Date': '2021-01-01'}
}
The ordered object should look like this:订购的 object 应如下所示:
a = {
3: {'Text': 'Test3', 'Date': '2021-01-01'},
1: {'Text': 'Test1', 'Date': '2021-05-11'},
2: {'Text': 'Test2', 'Date': '2021-12-12'}
}
I managed to do this with a list of dictionaries:我设法用字典列表做到了这一点:
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'])
But I cannot figure it out with a dictionary of dictionaries.但是我无法用字典来弄清楚。 Maybe someone can point me in the right direction.
也许有人可以指出我正确的方向。
Thanks in advance.提前致谢。 Frank
坦率
You need to use a.items()
and then use the key as key=lambda x:x[1]['Date']
.您需要使用
a.items()
,然后将密钥用作key=lambda x:x[1]['Date']
。 Second element of x
is the value. 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'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.