3

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?

Saigo no Akuma
  • 147
  • 1
  • 1
  • 11

2 Answers2

4

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.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

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.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186