Python

Python

Dictionary Comparison in Python

When you start working with Python dictionaries, one common task you'll encounter is comparing two dictionaries to understand their differences.

While comparing simple data types like integers or strings is straightforward, dictionary comparison presents unique challenges due to their complex nature and nested structures. This section explores various methods and best practices for comparing dictionaries in Python, from basic equality checks to deep comparison.

Practical Example

Picture yourself building a student management system where you need to track changes in student records. Each student's information is stored in a dictionary, and you want to know exactly what changed between two versions of their data.

Our comparison function works like a detective investigating the differences between two dictionaries. It examines both dictionaries thoroughly and creates a detailed report of what it finds. Think of it as comparing two versions of the same document - you want to know what was added, what was removed, and what was modified.

The function starts by looking at the most basic question: are these dictionaries exactly the same? It uses Python's built-in equality operator (==) to check this. However, it doesn't stop there. Just like a thorough detective, it digs deeper to find specific differences that might be important to know about.

Next, it looks at the keys in both dictionaries. Using Python's powerful set operations, it identifies which keys are unique to each dictionary and which keys they share in common. This is similar to comparing two lists of items and finding out what appears in both lists and what's unique to each list. For example, if one student record has an 'active' status and another has 'enrolled' status, our function will tell us about these different fields.

For the keys that exist in both dictionaries, the function goes one step further. It compares the values associated with these common keys. If it finds any differences, it records both values so you can see exactly what changed. This is particularly useful when tracking changes in grades, contact information, or any other student data that might be updated over time.

The beauty of this code lies in its versatility. While our example uses student records, the same function could be used to compare product inventories, game states, configuration files, or any other data stored in dictionary format. The function doesn't care what kind of data it's comparing – it simply reports the differences it finds.

Remember, while this code might look complex at first glance, it's really just doing what we often do mentally when comparing two things: checking what's the same, what's different, and keeping track of those differences in a organized way.

Using == operator

The simplest way to compare dictionaries is using the equality operators:

This operator checks if both dictionaries have the same keys and values.

Using Loop

We can use a simple loop to check each key and value. Here's how:

def compare_dicts(dict1, dict2):
    # First, check if they have the same number of items
    if len(dict1) != len(dict2):
        return False
    
    # Now check each key and value
    for key in dict1:
        # Check if the key exists in both dictionaries
        if key not in dict2:
            return False
        # Check if the values are the same
        if dict1[key] != dict2[key]:
            return False
    
    return True

Here are some fun examples to understand how it works:

my_pets = {
    "dog": "Rex",
    "cat": "Whiskers",
    "fish": "Nemo"
}
friends_pets = {
    "dog": "Rex",
    "cat": "Whiskers",
    "fish": "Nemo"
}
different_pets = {
    "dog": "Max",
    "cat": "Whiskers",
    "fish": "Goldie"
}
print(compare_dicts(my_pets, friends_pets))    # True
print(compare_dicts(my_pets, different_pets))  # False

Explanation:

  • my_pets == friends_pets evaluates to True because both have identical key-value pairs.
  • my_pets == different_pets evaluates to False because the values for key 'dog' differ.

Although Python provides built-in comparison operator, implementing dictionary comparison with loops gives you granular control over the process.

Using the DeepDiff Library

DeepDiff is specifically designed to handle deep comparisons of complex data structures, including lists and sets.

While the regular dictionary comparison we learned earlier is great for simple cases, DeepDiff is your go-to tool when things get complex.

Let's see it in action with a simple example:

Here are some cool tricks it can do:

  • Values that changed: "Hey, this price went from $10 to $15!"
  • Items that were added or removed: "This product got a new 'discount' field!"
  • Dictionary keys that changed: "The 'name' field was renamed to 'title'!"
  • Type changes: "This was a number, now it's text!"

You can also customize how DeepDiff works. Here are some handy options:

# Ignore specific keys
diff = DeepDiff(product1, product2, exclude_paths=["root['details']['color']"])

# Get the results in tree view
diff = DeepDiff(product1, product2, view='tree')

# Ignore order in lists
diff = DeepDiff(product1, product2, ignore_order=True)

DeepDiff is your best friend when you need to:

  • Tracking changes in configuration files
  • Watch how your data changes over time
  • Compare what your API sent vs what you expected
  • Quality assurance testing
  • Data validation processes

Want to learn all the amazing things DeepDiff can do? Check out the DeepDiff documentation

Comparison Methods for Python Dictionaries

Feature == Operator Using Loop DeepDiff
Syntax dict1 == dict2 requires writing loop logic DeepDiff(dict1, dict2)
Speed Fast Moderate Slower (especially for large dictionaries)
Nested Dictionary Support Basic Can be customized Excellent built-in support
Customization None High (can add custom logic, partial checks) Moderate (has configuration options: ignore keys, types, precision, etc.)
Learning Curve Very Easy Easy Moderate
External Dependencies Built-in Built-in Requires deepdiff package
Detailed Differences Only True/False result Can be customized to show differences Detailed report of all differences
Handling of Floating-Point Precision No Yes (custom logic) Yes (configurable precision tolerance)
Output Format Boolean Customizable Structured difference report
Best For Quick equality checks Learning and custom logic Production and complex data

FAQs on Dictionary Comparison in Python

How do I compare two dictionaries for equality?

You can use the == operator to check if two dictionaries have the same keys and values:

dict1 == dict2

How does Python check if two dictionaries are equal?

Python compares the key-value pairs of each dictionary. Two dictionaries are considered equal if they have the same keys, and each key is associated with the same value in both. The order of key insertion does not affect this comparison.

How can I check if one dictionary is a subset of another?

Use dictionary comprehension with the <= operator:

is_subset = dict1.items() <= dict2.items() 

How can I compare only the keys of two dictionaries?

You can compare the sets of keys directly, such as

set(dict1.keys()) == set(dict2.keys())

This approach checks if both dictionaries contain exactly the same keys.

What is the difference between == and is when comparing dictionaries?

The == operator checks if two dictionaries have the same content, while is checks if they are the same object in memory:

dict1 == dict2  # Compares values
dict1 is dict2  # Compares memory addresses

How do I find the differences between two dictionaries?

You can use set operations on items():

This approach will not work for nested dictionaries, as in Python dictionaries are mutable and, therefore, cannot be elements of a set. To correctly compare nested dictionaries, you need to use recursion or special libraries such as deepdiff.

Can I compare dictionaries based on specific keys only?

Yes, you can filter the dictionaries before comparison:

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.