Search code examples
pythonpython-3.xpython-datetime

Get id having the latest datetimestamp from dict


I am looking to retrieve the Machine VM id which has the latest creation datetimestamp value,

Below is the code but it returns incorrect value m3.

def get_machine_id_latest_datetimestamp(self):
    thisdict = {
        "machines-xyz-123": {
            "vm": {
                "id": "m1",
                "createTimestamp": "2020-11-27T09:44:02.272908941Z",
                "status": "running"
            }
        },

        "machines-abc-567": {
            "vm": {
                "id": "m2",
                "createTimestamp": "2020-11-27T23:15:22.212021105Z",
                "status": "running"
            }
        },

        "machines-vvy-569": {
            "vm": {
                "id": "m3",
                "createTimestamp": "2020-11-27T22:18:00.572021105Z",
                "status": "running"
            }
        },

        "machines-tgh-m4": {
            "vm": {
                "id": "m4",
                "createTimestamp": "2020-11-27T14:01:22.412621105Z",
                "status": "running"
            }
        }
    }


    machine_id_timestamp_dictionary = {}
    machines_count = len(thisdict)
    machine = list(thisdict.keys())

    for i in range (machines_count):
        machine_id = thisdict[machine[i]]["vm"]["id"]
        vw_creation_timestamp = \
            thisdict[machine[i]]['vm']['createTimestamp']
        machine_id_timestamp_dictionary[machine_id] = vw_creation_timestamp

    latest_created_machine_id = 0
    machine_filtered = set()

    for machine_id in machine_id_timestamp_dictionary:
        if machine_id_timestamp_dictionary[machine_id] > thisdict[machine[i]]['vm']['createTimestamp']:
            latest_created_machine_id = machine_id
            machine_filtered.add(latest_created_machine_id)
    print("Latest Created Machine ID")
    print(latest_created_machine_id)

Ideally the Machine ID m2 should be returned as it is the latest created id, Any pointers why the code is failing?


Solution

  • Since you have ISO format timestamps, you can sort on string (skipping the conversion to datetime is more efficient). Set reverse=True and just pick the first element:

    # assuming 'd' holds your nested dicts:
    sortedDicts = sorted(d.values(), key=lambda d: d['vm']['createTimestamp'], reverse=True)
    
    newestVmId = sortedDicts[0]['vm']['id']
    
    print(newestVmId)
    # m2