You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中查找嵌套字典中时间戳最大的条目对应的键?

Find the Latest Order by Maximum 'time' Value in a Nested Dictionary

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 key parameter in max() tells Python to compare each entry based on the 'time' value inside the order_details dict (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:12:31