python检查列表中的字典值是否重复

时间:2016-05-20 13:32:20

标签: python

我有一组数据,我想检查value中的data是否重复。
我的方法如下,我认为它有点复杂,所以我想问一下有更好的方法吗?

data =[
        {"name": "ali", 
         "value": "ABC" 
         },
        {"name": "bob", 
         "value": "ABC" 
         },
        {"name": "cathy", 
         "value": "ABC" 
         },
        {"name": "david", 
         "value": "ABCD" 
         },
    ]


check_list = []
duplicate_value = []
for d in data:
    if d["value"] not in check_list:
        check_list.append(d["value"]) 
    else:
        if d["value"] not in duplicate_value:
            duplicate_value.append(d["value"])


print  "You have duplicate value:", duplicate_value 

3 个答案:

答案 0 :(得分:3)

> cluster meet MASTER_IP MASTER_PORT
# wait several seconds, and use cluster nodes to ensure that it has joined the cluster

> cluster replicate MASTER_NODE_ID
# wait, and use cluster nodes to ensure it has become a slave

输出 -

from collections import Counter

data =[
        {"name": "ali", 
         "value": "ABC" 
         },
        {"name": "bob", 
         "value": "ABC" 
         },
        {"name": "cathy", 
         "value": "ABC" 
         },
        {"name": "david", 
         "value": "ABCD" 
         },
    ]

arr = [d['value'] for d in data]

duplicate_values = [k for k, v in Counter(arr).items() if v > 1]

print('Duplicate values - ', duplicate_values)

答案 1 :(得分:1)

你可以做一些简单的事情:

def has_duplicates(your_list):
    values = [item['value'] for item in your_list]

    return len(set(values)) < len(values)

def get_duplicates(your_list):
    values = [item['value'] for item in some_list]

    return [item for item in set(values) if values.count(item) > 1]

答案 2 :(得分:0)

您可以使用collections.Counter

>>> c = collections.Counter(d['value'] for d in data)
>>> c
Counter({'ABC': 3, 'ABCD': 1})
>>> duplicates = [k for k, n in c.most_common() if n > 1]
>>> duplicates
['ABC']