匹配两个词典中的键/值对并创建第三个词典

时间:2015-06-15 14:13:29

标签: python loops dictionary

我已经阅读了两个文件,我分别从中创建了带有ID及其对应序列的字典作为键和值。我试图找到两个字典中存在的键/值对,并创建一个只包含这些匹配的键值/值对。每个字典都有几千个键/值对。我的代码如下:

matched = {}
for i in data1.keys():
    for j in data2.keys():
        if i in j:
            matched = {i: data1[i]}
        else:
            pass

当我运行此片段时,我得到匹配一个键/值对,但是我已经计算了两个词组之间的匹配键(因此值),它们是2434.有人知道吗如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

问题在于这一行

matched = {i: data1[i]}

它会覆盖以前的字典值。它应该是

matched[i] = data1[i]

或者您可以使用update

matched.update({i: data1[i]})

答案 1 :(得分:1)

This is one way to do it, using dictionary comprehensions:

data3 = {k: v for k,v in data1.iteritems() if (k,v) in data2.iteritems()}

答案 2 :(得分:1)

Alternatively, you might use the fact that the keys method of dictionaries returns a set-like object, so you can take the intersection of two sets of keys:

>>> d1 = {'foo': 1, 'bar': 2, 'baz': 3}
>>> d2 = {'foo': 3, 'quux': 42, 'baz': 14}
>>> {key:d1[key] for key in d1.keys() & d2.keys()}
{'baz': 3, 'foo': 1}

If you're using Python 2, replace d1.keys() and d2.keys() with d1.viewkeys() and d2.viewkeys().