Python - 按 dict`as dict value 的值对字典列表进行排序
Python - Sort a list of dics by value of dict`s dict value
我有一个如下所示的列表:
persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}]
我需要根据子键的子键 - 他们的 birth_info 日期对人员列表进行排序。
我应该怎么做?
谢谢
试试这个
from datetime import datetime
print(sorted(persons, key=lambda x: datetime.strptime(x['passport']['birth_info']['date'], "%d/%m/%Y"))) #reverse=True for descending order.
函数sorted()
提供了key
参数。可以定义一个可调用的 returns 比较项目的键:
sorted(persons, key=lambda x: x['passport']['birth_info']['date'])
参数 x 是给定人员列表中的一项。
如果日期是字符串,您可以使用 datetime
模块:
sorted(persons, key=lambda x: datetime.datetime.strptime(x['passport']['birth_info']['date'], '%m/%d/%Y'))
我有一个如下所示的列表:
persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}]
我需要根据子键的子键 - 他们的 birth_info 日期对人员列表进行排序。
我应该怎么做? 谢谢
试试这个
from datetime import datetime
print(sorted(persons, key=lambda x: datetime.strptime(x['passport']['birth_info']['date'], "%d/%m/%Y"))) #reverse=True for descending order.
函数sorted()
提供了key
参数。可以定义一个可调用的 returns 比较项目的键:
sorted(persons, key=lambda x: x['passport']['birth_info']['date'])
参数 x 是给定人员列表中的一项。
如果日期是字符串,您可以使用 datetime
模块:
sorted(persons, key=lambda x: datetime.datetime.strptime(x['passport']['birth_info']['date'], '%m/%d/%Y'))