HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python dictionary intersection – compare two dictionaries

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 !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Examples

  • Python Hello World
  • Python Dictionary Intersection
  • Python Unpacking Tuple
  • Python Find Largest N Items
  • Python Finding Max and Min
  • Python Print to File
  • Python Print Without Newline
  • Python Print List

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)