我有以下列表:
[
{
"attributes":
[
{
"label": "Event Date",
"value": "Tue, 29 Jun 2021 18:30:00 GMT"
}
],
"event": "DT2"
},
{
"attributes":
[
{
"label": "DT3",
"value": true
},
{
"label": "Event Date",
"value": "Thu, 22 Jul 2021 18:30:00 GMT"
}
],
"event": "DT5"
},
{
"attributes": [
{
"label": "DT6",
"value": 1.0
},
{
"label": "Event Date",
"value": "Thu, 08 Jul 2021 18:30:00 GMT"
}
],
"event": "DT7"
}
]
以上数据为dict
的list
。每个dict
都有一个attributes
的list
。attriutes
也是一个有很多条目的字典和Event Date
。我必须根据Event Date
的升序对list中的所有字典进行排序。我们如何才能做到这一点?
按键排序
下面是一个简单的例子:my_list = [
{
"foo": 5,
"bar": 4,
},
{
"foo": 3,
"bar": 2,
},
{
"foo": 1,
"bar": 0,
},
]
# This will sort the list according to the "foo" in each dictionary.
my_list.sort(key=lambda dictionary: dictionary["foo"])
对于您的具体情况,由于它更复杂,我将创建一个函数而不是使用lambda表达式。此外,我将使用datetime
来帮助我比较日期字符串。
from datetime import datetime
def key_function(dictionary):
attributes = dictionary["attributes"]
for attribute in attributes:
if attribute["label"] == "Event Date":
date_string = attribute["value"]
date = datetime.strptime(date_string, "%a, %d %b %Y %X %Z")
# Compare dates according to their POSIX timestamp
# I am assuming the dates will be after 1970
return date.timestamp()
raise ValueError("Event Date attribute wasn't found")
my_list.sort(key=key_function)
您需要首先获得日期时间字符串,然后格式化日期时间字符串:
import datetime
lst = [
{
"attributes":
[
{
"label": "Event Date",
"value": "Tue, 29 Jun 2021 18:30:00 GMT"
}
],
"event": "DT2"
},
{
"attributes":
[
{
"label": "DT3",
"value": True
},
{
"label": "Event Date",
"value": "Thu, 22 Jul 2021 18:30:00 GMT"
}
],
"event": "DT5"
},
{
"attributes": [
{
"label": "DT6",
"value": 1.0
},
{
"label": "Event Date",
"value": "Thu, 08 Jul 2021 18:30:00 GMT"
}
],
"event": "DT7"
}
]
lst.sort(key=lambda x: datetime.datetime.strptime(next(attr["value"] for attr in x["attributes"] if attr["label"] == "Event Date"), "%a, %d %b %Y %X %Z"))
或者更可读的方式:
def check(x):
for attr in x["attributes"]:
if attr["label"] == "Event Date":
return datetime.datetime.strptime(attr["value"], "%a, %d %b %Y %X %Z")
lst.sort(key=check)
给了我:
[{'attributes': [{'label': 'Event Date',
'value': 'Tue, 29 Jun 2021 18:30:00 GMT'}],
'event': 'DT2'},
{'attributes': [{'label': 'DT6', 'value': 1.0},
{'label': 'Event Date', 'value': 'Thu, 08 Jul 2021 18:30:00 GMT'}],
'event': 'DT7'},
{'attributes': [{'label': 'DT3', 'value': True},
{'label': 'Event Date', 'value': 'Thu, 22 Jul 2021 18:30:00 GMT'}],
'event': 'DT5'}]