Reputation: 788
I would like to sort my versions
array based on the modified_datetime
key. I can definitely use one of the sorting algorithms to do it but I'm just wondering if there is an efficient way to do it in Python.
my_json = {
"versions": [
{
"migrated_versions": [
{
"modified_datetime": "2020-09-11T21:15:22.215Z"
}
],
},
{
"migrated_versions": [
{
"modified_datetime": "2020-09-11T21:14:19.162Z"
}
]
},
{
"migrated_versions": [
{
"modified_datetime": "2020-09-11T21:10:19.289Z"
}
]
}
]
}
Upvotes: 0
Views: 36
Reputation: 168824
Since the datetimes are ISO8601, which is lexicographically sortable, you can just use the sorted()
built-in (or list.sort()
) with the key=
argument:
sorted(my_json["versions"], key=lambda v: v["migrated_versions"][0]["modified_datetime"])
Upvotes: 2