Open In App

Python – Symmetric Difference of Dictionaries

Improve
Improve
Like Article
Like
Save
Share
Report

Given two Dictionaries, the task is to write a Python program to get the symmetric difference.

Examples:

Input : test_dict1 = {'Gfg' : 4, 'is' : 3, 'best' : 7, 'for' : 3, 'geek' : 4}, 
        test_dict2 = {'Gfg' : 4, 'is' : 3, 'good' : 7, 'for' : 3, 'all' : 4}
Output : {'all': 4, 'good': 7, 'best': 7, 'geek': 4}
Explanation : all, good, best and geek are mutually unique keys.
Input : test_dict1 = {'Gfg' : 4, 'is' : 3, 'good' : 7, 'for' : 3, 'geek' : 4},
        test_dict2 = {'Gfg' : 4, 'is' : 3, 'good' : 7, 'for' : 3, 'all' : 4}
Output : {'all': 4, 'geek': 4}
Explanation : all, geek are mutually unique keys.

Method #1 : Using ^ operator + keys() + dictionary comprehension

In this, We extract all the keys using keys(), and get a symmetric difference of all the keys using ^ operator. The required dictionary is compiled using dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Symmetric Difference of Dictionaries
# Using ^ operator + keys() + dictionary comprehension
 
# Initializing dictionaries
test_dict1 = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
test_dict2 = {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
 
# Printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Getting symmetric difference using ^ operation
res = {key: test_dict1[key] if key in test_dict1 else test_dict2[key]
       for key in test_dict1.keys() ^ test_dict2.keys()}
 
# Printing result
print("The symmetric difference : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
The original dictionary 2 is : {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
The symmetric difference : {'best': 7, 'geek': 4, 'all': 4, 'good': 7}

Time Complexity: O(n*n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method #2 : Using set.symmetric_difference() + keys()

In this, we perform the task of getting uncommon elements using the inbuilt function symmetric_difference() method. 

Python3




# Python3 code to demonstrate working of
# Symmetric Difference of Dictionaries
# Using set.symmetric_difference() + keys()
 
# initializing dictionaries
test_dict1 = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
test_dict2 = {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# computing sym. difference using set inbuilt function
res = {key: test_dict1[key] if key in test_dict1 else test_dict2[key] for key in
       set(test_dict1.keys()).symmetric_difference(test_dict2.keys())}
 
# printing result
print("The symmetric difference : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
The original dictionary 2 is : {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
The symmetric difference : {'good': 7, 'all': 4, 'geek': 4, 'best': 7}

Method #3: Using loop and conditional statements

We can iterate through the keys of both dictionaries and check if each key is present in only one of the dictionaries. If it is, we add it to a new dictionary along with its value.

Steps:

  1. Create an empty dictionary to store the symmetric difference.
  2. Iterate through the keys of the first dictionary.
  3. If a key is not in the second dictionary, add it to the new dictionary along with its value.
  4. Iterate through the keys of the second dictionary.
  5. If a key is not in the first dictionary, add it to the new dictionary along with its value.

Python3




# initializing lists
test_dict1 = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
test_dict2 = {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
 
# Empty tuple
result_dict = {}
 
for key in test_dict1:
    if key not in test_dict2:
        result_dict[key] = test_dict1[key]
 
for key in test_dict2:
    if key not in test_dict1:
        result_dict[key] = test_dict2[key]
 
# Printing answer
print(result_dict)


Output

{'best': 7, 'geek': 4, 'good': 7, 'all': 4}

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4:Using the setdefault() method and loops

Algorithm:

  1. Check for the keys in dict1 that are not present in dict2 and add them to the sym_diff dictionary. 
  2. It then checks for the keys in dict2 that are not present in dict1 and adds them to the sym_diff dictionary. 
  3. Finally, for the keys that are present in both dictionaries, it checks if their values are the same and only includes them in the sym_diff dictionary if they are different.

Steps:

  1. Initialize an empty dictionary.
  2. Loop through the keys and values of both dictionaries.
  3. Use the setdefault() method to add key-value pairs to the new dictionary if they don’t already exist.
  4. If they do exist, remove the key-value pair from the new dictionary.

Python3




# Initializing dictionary
dict1 = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
dict2 = {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
 
sym_diff = {}
 
# Iterating elements in dictionary
for key, value in dict1.items():
    if key not in dict2:
        sym_diff[key] = value
 
for key, value in dict2.items():
    if key not in dict1:
        sym_diff[key] = value
    else:
        if value != dict1[key]:
            sym_diff[key] = value
 
# Printing answer
print("The symmetric difference:", sym_diff)


Output

The symmetric difference: {'best': 7, 'geek': 4, 'good': 7, 'all': 4}

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 5: Using set() and items()

Steps:

  1. Two dictionaries, test_dict1, and test_dict2, are initialized with some key-value pairs.
  2. The symmetric difference of these dictionaries is computed using the ^ (XOR) operator on the set of keys of the dictionaries. This is achieved by first converting the keys of both dictionaries to sets using the set() function, and then using the XOR operator (^) on these sets to get the set of keys that are in one dictionary but not the other.
  3. For each key in the symmetric difference set obtained in step 2, the corresponding value is obtained from the respective dictionaries using the get() method. If the key is not present in one of the dictionaries, it returns the default value, which is the value from the other dictionary.
  4. A new dictionary is created with the key-value pairs obtained in step 3, and it is assigned to the variable res.
  5. The result, which is the symmetric difference between the two dictionaries, is printed using the print() function, which converts the dictionary to a string using the str() function.

Python3




# Python3 code to demonstrate working of
# Symmetric Difference of Dictionaries
# Using set() and items()
 
# initializing dictionaries
test_dict1 = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
test_dict2 = {'Gfg': 4, 'is': 3, 'good': 7, 'for': 3, 'all': 4}
 
# computing symmetric difference using set() and items()
res = {k: test_dict1.get(k, test_dict2.get(k))
       for k in set(test_dict1.keys()) ^ set(test_dict2.keys())}
 
# printing result
print("The symmetric difference : " + str(res))


Output

The symmetric difference : {'best': 7, 'good': 7, 'geek': 4, 'all': 4}

Time complexity: O(N), where n is the total number of keys in both dictionaries.
Auxiliary Space: O(N), because we need to create a new dictionary to store the symmetric difference.



Last Updated : 15 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads