Python 查找两个词典列表中的常见成员

Python 查找两个词典列表中的常见成员,python,dictionary,Python,Dictionary,这可能是重复的,但我能找到的最接近的是对我不起作用的 所以我有两个字典列表 y = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}] y = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}] 如何比较这两个列表,以便在两个列表的交点处比较结果。我不能把它转换成set,因为它说的是不可损坏类型(dict)你的问题和它的标题似乎不一致 两个列表的交集将是两个列表的公共元素。问题标题请求不

这可能是重复的,但我能找到的最接近的是对我不起作用的

所以我有两个字典列表

y = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]

如何比较这两个列表,以便在两个列表的交点处比较结果。我不能把它转换成set,因为它说的是不可损坏类型(dict)

你的问题和它的标题似乎不一致

两个列表的交集将是两个列表的公共元素。问题标题请求不在两个列表中的元素。你想要哪一个

对于交叉口,它不是很有效(时间为O(n^2)),但此列表理解可以:

>>> a = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
>>> b = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
>>> [d for d in a if d in b]
[{'a': 1, 'b': 2, 'c': 3}]
dict(或list)是不可散列的,但是元组是可散列的。您可以将dict列表转换为一组元组。执行交叉,然后转换回

要转换为一组元组的代码

y_tupleset = set(tuple(sorted(d.items())) for d in y)
将相交元组集转换回DICT列表的代码

y_dictlist = [dict(it) for it in list(y_tupleset)]
因此,完整的代码是:

y0 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y1 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]

y0_tupleset = set(tuple(sorted(d.items())) for d in y0)
y1_tupleset = set(tuple(sorted(d.items())) for d in y1)
y_inter = y0_tupleset.intersection(y1_tupleset)
y_inter_dictlist = [dict(it) for it in list(y_inter)]

print(y_inter_dictlist)
# prints the following line
[{'a': 1, 'c': 3, 'b': 2}]
编辑:
d.items()
在python3上有效,对于python2,应将其替换为
d.iteritems()

选择毒药:

y1 = [{'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
y2 = [{'a': 4, 'b': 5, 'c': 6}, {'a': 1, 'b': 2, 'c': 3}]
y3 = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 2, 'c': 6}]

# Returns a list of keys that are in both dictionaries
def intersect_keys(d1, d2):
    return [k for k in d1 if k in d2]

# Returns a list of values that are in both dictionaries
def intersect_vals(d1, d2):
    return [v for v in d1.itervalues() if v in d2.itervalues()]

# Returns a list of (key,value) pairs that are in both dictionaries
def intersect_pairs(d1, d2):
    return [(k,v) for (k,v) in d1.iteritems() if k in d2 and d2[k] == v]


print(intersect_keys(*y1))      # ['a', 'c', 'b']
print(intersect_vals(*y1))      # [3]
print(intersect_pairs(*y1))     # []

print(intersect_keys(*y2))      # ['a', 'c', 'b']
print(intersect_vals(*y2))      # []
print(intersect_pairs(*y2))     # []

print(intersect_keys(*y3))      # ['a', 'c', 'b']
print(intersect_vals(*y3))      # [2]
print(intersect_pairs(*y3))     # [('b', 2)]
注意:这些示例比较了
y*
列表中的两个元素,这就是我对您的问题的解释。当然,您可以使用以下内容:

print(intersect_pairs(y1[0], y2[0]))

要计算交点,请使用
y1
y2
列表中的第一个字典。

确定交点时要考虑什么?钥匙?价值观?键/值对?从问题来看,他指的似乎是键-值对。预期的输出是什么?您如何定义这种“交集”?
print(intersect_pairs(y1[0], y2[0]))