Title: Compare Two Dictionaries
Slug: compare_two_dictionaries
Summary: Compare Two Dictionaries Using Python.
Date: 2017-02-02 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
One of the great features of Python dictionaries is that they are hashtables, meaning we can do some operations at O(1) time-complexity.
In [1]:
importers = {'El Salvador' : 1234,
'Nicaragua' : 152,
'Spain' : 252
}
exporters = {'Spain' : 252,
'Germany' : 251,
'Italy' : 1563
}
In [2]:
# Find the intersection of importers and exporters
importers.keys() & exporters.keys()
Out[2]:
In [3]:
# Find the difference between importers and exporters
importers.keys() - exporters.keys()
Out[3]:
In [4]:
# Find countries where the amount of exports matches the amount of imports
importers.items() & exporters.items()
Out[4]: