如何在python中检测dict数组中的重复键值?

use*_*139 1 python dictionary

鉴于以下代码:

a = [{"name": "Sport"}, {"name": "Games"}, {"name": "Videos"}, {"name": "Sport"}]
Run Code Online (Sandbox Code Playgroud)

如何判断变量中的另一个dict是否具有相同的名称值?在上面的示例中,结果应返回"Sport".

提前致谢.

Ada*_*ith 9

有很多好方法可以做到.Python中的规范可能是使用collections.Counter

from collections import Counter

c = Counter([d['name'] for d in a])
for value,count in c.items():
    if count > 1:
        print(value)
Run Code Online (Sandbox Code Playgroud)

如果您需要知道的是某些内容是否重复(不是重复多少次),您只需使用一seen组就可以简化.

seen = set()
for d in a:
    val = d['name']
    if val in seen:
        print(val)
    seen.add(val)
Run Code Online (Sandbox Code Playgroud)

可能最过度设计的方法是按照"名称"值对dicts进行排序,然后运行groupby并检查每个组的长度.

from itertools import groupby
from operator import itemgetter

namegetter = itemgetter('name')

new_a = sorted(a, key=namegetter)

groups = groupby(new_a, namegetter)

for groupname, dicts in groups:
    if len(list(dicts)) > 1:
        print(groupname)
Run Code Online (Sandbox Code Playgroud)