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

基于含日期键的字典生成各唯一值对应最新日期的新字典

Solution to Map Unique Values to Their Latest Occurrence Date

Let's break down how to solve this problem. The goal is to find, for each unique value in your original dictionary, the most recent date it appeared, then structure the result as a dictionary where each key is that latest date, and the value is a list of all unique values that last showed up on that date.

Step-by-Step Approach

  • First, we'll sort the dates from oldest to newest. This way, when we iterate through them, later (newer) dates will overwrite any earlier entries for the same value—ensuring we always keep the latest date for each value.
  • We'll use a temporary dictionary to track each value's latest date.
  • Finally, we'll reverse that temporary mapping to group values by their latest date, creating the desired output structure.

Code Implementation

# Your original dictionary
dicti_1 = {
    '2017-09-01': ['PRUEBAPRUEBA', 'PRUEBA123123'],
    '2017-10-03': ['PRUEBAPRUEBA', 'PRUEBA123123'],
    '2017-11-08': ['PRUEBAPRUEBA', 'PRUEBA123123'],
    '2017-12-03': ['PRUEBA123123']
}

# Step 1: Sort the dates in ascending order (oldest to newest)
sorted_dates = sorted(dicti_1.keys())

# Step 2: Track each value's latest date
value_to_latest_date = {}
for date in sorted_dates:
    values = dicti_1[date]
    for val in values:
        # Overwrite with the current (newer) date
        value_to_latest_date[val] = date

# Step 3: Group values by their latest date to form the result
result = {}
for val, date in value_to_latest_date.items():
    if date not in result:
        result[date] = []
    result[date].append(val)

print(result)
# Output: {'2017-11-08': ['PRUEBAPRUEBA'], '2017-12-03': ['PRUEBA123123']}

Explanation

  • By sorting the dates first, we ensure that when we process each date, any value in that date's list will update its entry in value_to_latest_date to the current (newer) date. So by the end of the loop, every value maps to its most recent occurrence date.
  • The final step just rearranges that mapping to group all values that share the same latest date under that date key, which matches exactly what you need.

内容的提问来源于stack exchange,提问作者JamesHudson81

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:52:27