如何合并具有相同键的两个词典并保留存在于同一键中的值

时间:2017-03-27 18:43:15

标签: python python-3.x dictionary merge

例如:

Dictionary1={'A' :['B','C','D'],'B' :['A']}
Dictionary2={'A' :['A','B'],    'B' :['A','F']}

我想要这个结果:

Merge={'A' :['B'],'B' :['A']}

因为只有' B'是在A' A'并且只有' B'在' B'

下的两个词典中都有

2 个答案:

答案 0 :(得分:0)

def intersect(c1, c2):
    """Intersection of two iterables (e.g. lists) in the order of the first, as a list"""
    c2 = set(c2)  # for faster lookup
    return [x for x in c1 if x in c2]  # this is called a list comprehension

Dictionary1 = {'A': ['B', 'C', 'D'], 'B': ['A']}
Dictionary2 = {'A': ['A', 'B'], 'B': ['A', 'F']}

# Here the .keys() is purely for clarity, as iterating over a dictionary already yields its keys
Merge = {k: intersect(Dictionary1[k], Dictionary2[k]) for k in Dictionary1.keys()}

print(Merge)  # {'A': ['B'], 'B': ['A']}

答案 1 :(得分:0)

def intersect(a, b):
    a, b = set(a), set(b)
    return list(a & b)


def merge_dicts(d1, d2):
    return {k: intersect(v1, v2) for (k, v1), v2 in zip(d1.items(), d2.values())}


dictionary_1 = {'A' :['B','C','D'],'B' :['A']}
dictionary_2 = {'A' :['A','B'],    'B' :['A','F']}

merge = merge_dicts(dictionary_1, dictionary_2)
print(merge) # {'A': ['B'], 'B': ['A']}