Home > Enterprise >  How to parse Value in OrderedDict and then sort it?
How to parse Value in OrderedDict and then sort it?

Time:03-19

I have a multidimensional OrderedDict and the value from the key "stampdate" is a string and i have to parse it in a datetime-format and then i want to sort it.

#############################################################

Here is my current Ordered Dict:

[
OrderedDict(
    [
        ("id", 56),
        ("werkzeug", 1006),
        ("stampdate", "2021-12-12T10:48:19.735532"),
        ("aktivstatus", "1"),
    ]
),
OrderedDict(
    [
        ("id", 57),
        ("werkzeug", 1006),
        ("stampdate", "2021-12-15T10:49:33.876611"),
        ("aktivstatus", "1"),
    ]
),
OrderedDict(
    [
        ("id", 60),
        ("werkzeug", 1006),
        ("stampdate", "2021-12-12T13:42:46.216805"),
        ("aktivstatus", "1"),
    ]
),
OrderedDict(
    [
        ("id", 230),
        ("werkzeug", 1006),
        ("stampdate", "2022-01-11T21:40:39.489662"),
        ("aktivstatus", "1"),
    ]
),
]

The Result should look like this way:

[
OrderedDict(
    [
        ("id", 56),
        ("werkzeug", 1006),
        ("stampdate", "2021-12-12T10:48:19.735532"),
        ("aktivstatus", "1"),
    ]
),

OrderedDict(
    [
        ("id", 60),
        ("werkzeug", 1006),
        ("stampdate", "2021-12-12T13:42:46.216805"),
        ("aktivstatus", "1"),
    ]
),

OrderedDict(
    [
        ("id", 57),
        ("werkzeug", 1006),
        ("stampdate", "2021-12-15T10:49:33.876611"),
        ("aktivstatus", "1"),
    ]
),
OrderedDict(
    [
        ("id", 230),
        ("werkzeug", 1006),
        ("stampdate", "2022-01-11T21:40:39.489662"),
        ("aktivstatus", "1"),
    ]
),
]

CodePudding user response:

>>> from datetime import datetime
>>> sorted(list_of_odered_dicts,key=lambda x: datetime.strptime(x['stampdate'], '%Y-%m-%dT%H:%M:%S.%f'))
[OrderedDict([('id', 56), ('werkzeug', 1006), ('stampdate', '2021-12-12T10:48:19.735532'), ('aktivstatus', '1')]), OrderedDict([('id', 60), ('werkzeug', 1006), ('stampdate', '2021-12-12T13:42:46.216805'), ('aktivstatus', '1')]), OrderedDict([('id', 57), ('werkzeug', 1006), ('stampdate', '2021-12-15T10:49:33.876611'), ('aktivstatus', '1')]), OrderedDict([('id', 230), ('werkzeug', 1006), ('stampdate', '2022-01-11T21:40:39.489662'), ('aktivstatus', '1')])]
  • Related