简体   繁体   English

根据字典列表中的两个值获取字典列表

[英]Get the list of dictionaries based on two values from the list of dictionaries

The list of dictionaries looks like: 词典列表如下:

lst_dict = [{'type': 'email', 'count': '180', 'date': '2019-04-22'},
            {'type': 'text', 'count': '12', 'date': '2018-12-20'},
            {'type': 'email', 'count': '150','date': '2018-12-20'}]

I am interested in getting the unique list of elements by type and with latest date. 我对按类型和最新日期获取元素的唯一列表感兴趣。 So, expected outcome is: 因此,预期结果是:

[{'type': 'email', 'count': '180', 'date': '2019-04-22'},
{'type': 'text', 'count': '12', 'date': '2018-12-20'}]

To get the unique elements by type I did: 要按类型获取唯一元素,我做了:

list({item['type']: item for item in lst_dict}.values())

The outcome is: 结果是:

[{'type': 'email', 'count': '150', 'date': '2018-12-20'},
 {'type': 'text', 'count': '12', 'date': '2018-12-20'}]

But it does not give the element by latest date.Tried different possibilities but got no luck. 但这并没有提供最新的信息,尝试了各种可能性,但没有运气。

Here's one way using itertools.groupby : 这是使用itertools.groupby的一种方法:

from itertools import groupby
l = sorted(lst_dict, key=lambda x: x['type'])
[max(list(v), key=lambda x: x['date']) for _,v in groupby(l, key=lambda x: x['type'])]

Output 产量

[{'count': '180', 'date': '2019-04-22', 'type': 'email'},
 {'count': '12', 'date': '2018-12-20', 'type': 'text'}]

If you want to keep your code you can sort the list by date in advance, it seems like your line of code will take the last entry in the list that matches the same type. 如果您想保留代码,则可以按日期提前对列表进行排序,似乎您的代码行将采用列表中与相同类型匹配的最后一个条目。

lst_dict = [{'type': 'email', 'count': '180', 'date': '2019-04-22'},
            {'type': 'text', 'count': '12', 'date': '2018-12-20'},
            {'type': 'email', 'count': '150','date': '2018-12-20'}]
lst_dict.sort(key=lambda x: x['date'])
print(list({item['type']: item for item in lst_dict}.values()))

My solution: 我的解决方案:

d = {}
for elem in lst_dict:
    if elem['type'] not in d: 
        d[elem['type']] = elem
    if elem['date'] > d[elem['type']]['date']: 
        d[elem['type']]=elem

You create a new dict, add a new entry for each type, and replace that entry if you have a newer date (only works in that specific date format, not really recommended). 您创建一个新的dict,为每种类型添加一个新的条目,如果您的日期更新,请替换该条目(仅适用于该特定日期格式,不建议这样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM