Python-按dict的dict值对dic列表进行排序 [英] Python - Sort a list of dics by value of dict`s dict value

查看:39
本文介绍了Python-按dict的dict值对dic列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表:

I have a list that looks like this:

persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}]

我需要按人员的子关键字-生日信息的日期对人员列表进行排序.

I need to sort the list of persons by their sub key of sub key - their birth_info date.

我应该怎么做?谢谢

推荐答案

函数 sorted()提供了 key 参数.可以定义一个可调用的方法,该方法返回用于比较各项的键:

The function sorted() provides the key argument. One can define a callable which returns the key to compare the items:

sorted(persons, key=lambda x: x['passport']['birth_info']['date'])

自变量x是给定人员列表中的一项.

The argument x is an item of the given list of persons.

如果日期是字符串,则可以使用 datetime 模块:

If the dates are strings you could use the datetime module:

sorted(persons, key=lambda x: datetime.datetime.strptime(x['passport']['birth_info']['date'], '%m/%d/%Y'))

这篇关于Python-按dict的dict值对dic列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆