0
votes

I have read two files from which I created dictionaries with IDs and their corresponding sequences as keys and values, respectively. I am trying to find the key/value pairs that exist in both dictionaries and to create a new one containing only these matching ones. Each dictionary has a couple thousand key/value pairs. My code is as follows:

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

When I run this snippet I get matched with a single key/value pair, however I have counted the matching keys (and therefore values) between the two dicts and they are 2434. Does anybody know how to fix this?

3
Thanks all for the quick answers, I've always beet weary of list comprehensions as they make the code look somewhat complicated but I understand they are usually faster? - Spyros

3 Answers

1
votes

The problem is this line

matched = {i: data1[i]}

It is overwriting the previous values of the dictionary. It should be

matched[i] = data1[i]

Or you can use update

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

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

1
votes

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