首页 > 解决方案 > 删除带有条件的列表中的字典

问题描述

我有下面的字典列表,我需要删除具有相同received_oncustomer_group值的字典,但留下一个随机的项目。

data = [
    {
        'id': '16e26a4a9f97fa4f',
        'received_on': '2019-11-01 11:05:51',
        'customer_group': 'Life-time Buyer'
    },
    {
        'id': '16db0dd4a42673e2',
        'received_on': '2019-10-09 14:12:29',
        'customer_group': 'Lead'
    },
    {
        'id': '16db0dd4199f5897',
        'received_on': '2019-10-09 14:12:29',
        'customer_group': 'Lead'
    }
]

预期输出:

[
    {
        'id': '16e26a4a9f97fa4f',
        'received_on': '2019-11-01 11:05:51',
        'customer_group': 'Life-time Buyer'
    },
    {
        'id': '16db0dd4199f5897',
        'received_on': '2019-10-09 14:12:29',
        'customer_group': 'Lead'

    }
]

标签: pythonpython-3.x

解决方案


使用上面的一些想法,我还想customer_groupreceived_on. 我得到了我的预期结果。

conditions, result = [], []
for d in data:
    condition = (d['received_on'], d['customer_group'])
    if condition not in conditions:
        result.append(d)
        conditions.append(condition)
print(len(result))

推荐阅读