Saigo no Akuma
Saigo no Akuma

Reputation: 147

Merge Two Dictionaries that Share Same Key:Value

I know this can be done with lists, but I'm just trying to figure out how to do this with dictionaries.

Basically, it'll go like this:

dict1 = {'a': 10, 'b': 12, 'c': 9}
dict2 = {'a': 10, 'b': 3, 'c': 9}

def intersect(dict1, dict2):
    combinDict = dict()


....
print(combinDict)
{'a': 10, 'c':9}

So I only want the keys with the same value added into a new dictionary.

Any help?

Upvotes: 3

Views: 215

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 77093

Another way to do this would be to use a dict comprehension:

In [1]: dict1 = {'a': 10, 'b': 12, 'c': 9}

In [2]: dict2 = {'a': 10, 'b': 3, 'c': 9}

In [3]: {key: dict1[key] for key in dict1 if dict1[key] == dict2.get(key)}
Out[3]: {'a': 10, 'c': 9}

This should be teeny weeny bit faster, though that wouldn't matter for regular dictionaries.

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

You want the intersection of the items:

dict1 = {'a': 10, 'b': 12, 'c': 9}
dict2 = {'a': 10, 'b': 3, 'c': 9}

print dict(dict1.viewitems() & dict2.items())
{'a': 10, 'c': 9}

For python 3 you just want to use items:

 dict(dict1.items() & dict2.items())

dict1.items() & dict2.items() returns a set of key/value pairings that are common to both dicts:

In [4]: dict1.viewitems() & dict2.items()
Out[4]: {('a', 10), ('c', 9)}

Then we simply call the dict constructor on that.

Upvotes: 4

Related Questions