HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Python dictionary intersection – compare two dictionaries

By Lokesh Gupta | Filed Under: Python

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

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

Leave a Reply

This comment form is under antispam protection
This comment form is under antispam protection
  Subscribe  
Notify of

Search Tutorials

Python Tutorial

  • Python – Install In Sublime Editor
  • Python – Read/Write CSV Files
  • Python – httplib2
  • Python – Unpack Tuple
  • Python – Unpack Variable Lengths
  • Python – max() and min()
  • Python – Largest/Smallest N items
  • Python – multidict
  • Python – OrderedDict
  • Python – dictionary intersection
  • Python – Split string
  • Python – startswith
  • Python – endswith
  • Python – Priority Queue

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz