Python dictionary intersection – compare two dictionaries

Python examples to find common items between 2 or more dictionaries i.e. dictionary intersection items.

1. Dictionary intersection using ‘&’ operator

Simplest method is to find intersections of keys, values or items is to use & operator between two dictionaries.

a = { 'x' : 1, 'y' : 2, 'z' : 3 }
b = { 'u' : 1, 'v' : 2, 'w' : 3, 'x'  : 1, 'y': 2 }

set( a.keys() ) & set( b.keys() )   	# Output set(['y', 'x'])

set( a.items() ) & set( b.items() )   	# Output set([('y', 2), ('x', 1)])

2. Set intersection() method

Set intersection() method return a set that contains the items that exist in both set a, and set b.

a = { 'x' : 1, 'y' : 2, 'z' : 3 }
b = { 'u' : 1, 'v' : 2, 'w' : 3, 'x'  : 1, 'y': 2 }

setA = set( a )
setB = set( b )

setA.intersection( setB )  

# Output 
# set(['y', 'x'])

for item in setA.intersection(setB):
    print item

# Output 
#x
#y

Drop me your questions related to checking if two dictionaries have same keys or values in python.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.