How do I find the latest entry in a nested dictionary using the time stored in nested dictionary items? (Python)

Viewed 30

I have a dictionary that looks like this (the dictionary has 4.000+ entries)

{'order': {'T2DZVX-OD7YQ3':  {'cost': '19.95',
                              'ordertxid': 'OYKRY2-E6VJZ',
                              'time': 1649666120.6187882,
                              },
           'T2V5ZF-U7VCII':  {'cost': '14.95',
                              'ordertxid': 'QVLNT-BRSIQX',
                              'time': 1650276000.0017374,
                              },
           'T47WOA-5GR52B':  {'cost': '24.95',
                              'ordertxid': 'OVT5LL-WHDX3',
                              'time': 1649366792.625624}}}

How do I find the key? In this case "T2V5ZF-U7VCII" where the 'time' is the highest number? (newest entry)

1 Answers

Use max on the different orders pairs using the good sorting key

values = {'order': {
    'T2DZVX-OD7YQ3': {'cost': '19.95', 'ordertxid': 'OYKRY2-E6VJZ', 'time': 1649666120.6187882, },
    'T2V5ZF-U7VCII': {'cost': '14.95', 'ordertxid': 'QVLNT-BRSIQX', 'time': 1650276000.0017374, },
    'T47WOA-5GR52B': {'cost': '24.95', 'ordertxid': 'OVT5LL-WHDX3', 'time': 1649366792.625624}}
}

x = max(values['order'].items(), key=lambda x: x[1]['time'])
print(x)  # ('T2V5ZF-U7VCII', {'cost': '14.95', 'ordertxid': 'QVLNT-BRSIQX', 'time': 1650276000.0017374})
print(x[0])  # T2V5ZF-U7VCII
Related