如何在Python中查找嵌套字典中时间戳最大的条目对应的键?
Hey there! Here's a concise and efficient way to get the order ID with the largest 'time' value from your nested dictionary:
Step-by-Step Solution
First, let's assume your data is stored in a variable called order_data (adjust the name to match your actual variable):
order_data = { '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} } } # Extract the inner dictionary of orders orders = order_data['order'] # Find the order with the maximum 'time' value latest_order_id = max(orders.items(), key=lambda item: item[1]['time'])[0] print(latest_order_id) # Output: T2V5ZF-U7VCII
How This Works
orders.items()gives us a list of tuples like(order_id, order_details)for every entry in your dictionary.- The
keyparameter inmax()tells Python to compare each entry based on the'time'value inside theorder_detailsdict (using a lambda function to access that value). - The
max()function returns the tuple with the largest 'time' value, and we take the first element[0]to get the order ID.
Why This Is Great for Your 4000+ Entries
This approach runs in O(n) time (it only iterates through your dictionary once), which is efficient even for large datasets like yours. No need for manual loops or tracking variables—Python's built-in max() handles all the heavy lifting.
Edge Case Note
If some entries might be missing the 'time' key, you can add a fallback to avoid errors, like:
latest_order_id = max(orders.items(), key=lambda item: item[1].get('time', 0))[0]
This uses get() to default to 0 if 'time' is missing, ensuring the code doesn't crash.
内容的提问来源于stack exchange,提问作者F.Goldschmied

