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

时间:2015-03-26 03:50:32

标签: python dictionary

这可能是重复的,但我能找到的最接近的是Comparing 2 lists consisting of dictionaries with unique keys in python这对我不起作用。

所以我有两个词典列表。

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}]

如何比较这两个列表,以便我的比较结果在两个列表的交集处。我无法将其转换为设置,因为它表示不可用类型(字典)

4 个答案:

答案 0 :(得分:4)

你的问题和它的标题似乎相互矛盾。

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

对于交集,它不是很有效(在时间上是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}]

答案 1 :(得分:2)

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}]
print [x for x in y1 if x in y2] # prints [{'a': 1, 'c': 3, 'b': 2}]

答案 2 :(得分:1)

dict(或列表)不可清除,但是,元组是。您可以将dicts列表转换为一组元组。执行交集然后转换回来

转换为一组元组的代码

y_tupleset = set(tuple(sorted(d.items())) for d in y)

将相交的元组转换回dicts of the dicts的代码

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()

答案 3 :(得分:0)

选择你的毒药:

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]))

计算y1y2列表中第一个字典的交集。

相关问题