【问题标题】:Is there a way to filter a list of dictionaries based on a value in one dictionary being less than the same key in another?有没有办法根据一个字典中的值小于另一个字典中的相同键来过滤字典列表?
【发布时间】:2021-01-27 22:13:21
【问题描述】:

对于令人费解的标题,我深表歉意。我需要按相当具体的标准过滤字典列表。

通常,我会做一个列表理解,但我对逻辑并不积极。

这是一个示例列表:

list_dict = [{'item_id': '000354', 'ts_created': '11/12/2013', 'item_desc': 'a product'},
             {'item_id': '000354', 'ts_created': '11/13/2013', 'item_desc': 'a product'},
             {'item_id': '000355', 'ts_created': '11/12/2013', 'item_desc': 'a different product'}]

您会注意到除了 'ts_created' 之外,前两个字典项是相同的。

我想创建一个新字典,保留所有具有最早时间戳的项目,并丢弃其余的。

编辑:从标题中删除“优雅”,因为它似乎冒犯了一些人。

编辑 2:试图改进标题。

编辑 3(焦点?):我真的不知道如何再关注这个问题,但我会尝试。参考上面的示例代码(实际列表要大得多),列表中有重复的字典。它们的唯一区别是“ts_created”值。我只想保留唯一的“item_id”字典,以及最早的“ts_created”。结果列表如下所示。

list_dict = [{'item_id': '000354', 'ts_created': '11/12/2013', 'item_desc': 'a product'},
             {'item_id': '000355', 'ts_created': '11/12/2013', 'item_desc': 'a different product'}]

【问题讨论】:

  • 请将您的 not-elegant-enough-for-your-tastes 代码编辑为 minimal reproducible example。我的建议是,如果您对列表推导或生成器表达式没有信心,那么只需将它们编写为 for 循环 - 使用 for 循环意味着您可以调试或添加打印语句以查看正在发生的事情,这在单行中都不可能。
  • 您好 ZombieDev,欢迎来到 Stack Overflow!请帮助我更好地理解要求。目标是从最早的ts_created 日期的字典列表中返回字典吗?如果有多个字典具有相同的最早ts_created 日期,是否将它们作为字典列表返回?
  • 这能回答你的问题吗?首先使用ts_created 排序,然后删除重复项。步骤 1.How do I sort a list of dictionaries by a value of the dictionary? 步骤 2.Remove duplicates from a list of dictionaries when only one of the key values is different
  • 编辑了我的问题以提高清晰度。 @aneroid 这些链接非常有帮助!本质上,将它们分解、排序,然后构建一个新的字典列表。感谢您的帮助。
  • 不客气。欢迎来到 StackOverflow。一个能得到答案的好问题的要求之一是发布您尝试过的代码,而不仅仅是“这就是我所拥有的,这就是我想要的,去为我做吧” ,即使你不是故意的。很高兴这两个链接(步骤)有所帮助。在尝试解决方案时,如果您遇到特定问题,请发布另一个问题或编辑此问题。 PS。我将其作为我链接的 1/2 的 重复 问题关闭。

标签: python dictionary filter list-comprehension


【解决方案1】:

您可以使用以 item_id 为键的字典来过滤字典。当您填充该索引字典时,仅保留具有最大时间戳的项目。由于您的时间戳是未按国际标准格式化的字符串,因此您需要将它们转换为实际日期以进行比较。第二个字典(在 item_id 上也有索引)可用于跟踪转换后的时间戳。

list_dict = [{'item_id': '000354', 'ts_created': '11/12/2013', 'item_desc': 'a product'},
             {'item_id': '000354', 'ts_created': '11/13/2013', 'item_desc': 'a product'},
             {'item_id': '000355', 'ts_created': '11/12/2013', 'item_desc': 'a different product'}]

from datetime import datetime
maxDates = dict()  # association between item and timestamp
result   = dict()  # indexed single instance result (dictionary of dictionaries)
for d in list_dict:
    key       = d['item_id']
    timestamp = datetime.strptime(d['ts_created'], '%m/%d/%Y') # usable timestamp
    if itemId not in result or timestamp>maxDates[key]:        # keep only latest
        result[key]   = d
        maxDates[key] = timestamp
result = list(result.values())    # convert back to a list of dictionaries

print(result)
        
[{'item_id': '000354', 'ts_created': '11/13/2013', 'item_desc': 'a product'},
 {'item_id': '000355', 'ts_created': '11/12/2013', 'item_desc': 'a different product'}]

如果唯一性由多个字段确定(而不仅仅是 item_id),则需要将所有值组合到一个键中。

例如(对于除时间戳之外的所有字段):

key = tuple(d[k] for k in sorted(d) if k != 'ts_created')

【讨论】:

    【解决方案2】:

    您可以使用pandas.DataFrame,按日期排序,然后删除所有重复项。

    import pandas
    
    df = pandas.DataFrame(list_dict)
    # To datetime
    df['ts_created'] = pandas.to_datetime(df['ts_created'])
    # Sort by item_id, then by date
    df.sort_values(by=['item_id', 'ts_created'], inplace=True)
    # Drop duplicates, leaving only the first item_id
    df.drop_duplicates(subset=['item_id'], keep='first', inplace=True)
    # Convert the dates back to the original format
    df['ts_created'] = df.ts_created.dt.strftime('%m/%d/%Y')
    # Create the list again
    df.to_dict(orient='records')
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 2017-11-06
      • 1970-01-01
      • 2021-06-03
      • 2022-06-23
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      相关资源
      最近更新 更多