查找作为列表的字典值的交集

时间:2016-07-15 07:45:21

标签: python

我在具有相同键的列表中有字典,而值是变体:

[{1:[1,2,3,4,5], 2:[6,7,8], 3:[1,3,5,7,9]},
 {1:[2,3,4], 2:[6,7], 3:[1,3,5]},
 ...]

我想在相同的键下得到十字架作为字典:

{1:[2,3,4], 2:[6,7], 3:[1,3,5]}

4 个答案:

答案 0 :(得分:0)

试一试?

dicts = [{1:[1,2,3,4,5], 2:[6,7,8], 3:[1,3,5,7,9]},{1:[2,3,4], 2:[6,7], 3:[1,3,5]}]

result = { k: set(dicts[0][k]).intersection(*(d[k] for d in dicts[1:])) for k in dicts[0].keys() }

print(result)

# Output:
# {1: {2, 3, 4}, 2: {6, 7}, 3: {1, 3, 5}}

如果您希望列表而不是集合作为输出值类型,只需在集合交叉点周围抛出list(...)

答案 1 :(得分:0)

对于词典列表,请将整个列表缩小为:

>>> from functools import reduce
>>> d = [{1:[1,2,3,4,5], 2:[6,7,8], 3:[1,3,5,7,9]},{1:[2,3,4], 2:[6,7], 3:[1,3,5]}]
>>> reduce(lambda x, y: {k: sorted(list(set(x[k])&set(y[k]))) for k in x.keys()}, d)
{1: [2, 3, 4], 2: [6, 7], 3: [1, 3, 5]}

答案 2 :(得分:0)

我可能会沿着这些方向做点什么:

# Take the first dict and convert the values to `set`.
output = {k: set(v) for k, v in dictionaries[0].items()}

# For the rest of the dicts, update the set at a given key by intersecting it with each of the other lists that have the same key.
for d in dictionaries[1:]:
    for k, v in output.items():
        output[k] = v.intersection(d[k])

在同一个主题上有不同的变体,但我发现这个变体看起来很简单(并且由于代码的读取次数比写入时更频繁,我认为这是一个胜利: - )

答案 3 :(得分:0)

使用dict.viewkeysdict.viewitems

In [103]: dict.viewkeys?
Docstring: D.viewkeys() -> a set-like object providing a view on D's keys

dict.viewitems?
Docstring: D.viewitems() -> a set-like object providing a view on D's items

a = [{1: [1, 2, 3, 4, 5], 2: [6, 7, 8], 3: [1, 3, 5, 7, 9]},
 {1: [2, 3, 4], 2: [6, 7], 3: [1, 3, 5]}]

In [100]: dict(zip(a[0].viewkeys() and a[1].viewkeys(), a[0].viewvalues() and a[1].viewvalues()))
Out[100]: {1: [2, 3, 4], 2: [6, 7], 3: [1, 3, 5]}