Python - Symmetric Difference of Dictionaries
Last Updated :
15 May, 2023
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))
OutputThe 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))
OutputThe 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:
- Create an empty dictionary to store the symmetric difference.
- Iterate through the keys of the first dictionary.
- If a key is not in the second dictionary, add it to the new dictionary along with its value.
- Iterate through the keys of the second dictionary.
- 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:
- Check for the keys in dict1 that are not present in dict2 and add them to the sym_diff dictionary.
- It then checks for the keys in dict2 that are not present in dict1 and adds them to the sym_diff dictionary.
- 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:
- Initialize an empty dictionary.
- Loop through the keys and values of both dictionaries.
- Use the setdefault() method to add key-value pairs to the new dictionary if they don't already exist.
- 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)
OutputThe 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:
- Two dictionaries, test_dict1, and test_dict2, are initialized with some key-value pairs.
- 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.
- 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.
- A new dictionary is created with the key-value pairs obtained in step 3, and it is assigned to the variable res.
- 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))
OutputThe 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.
Similar Reads
Python | Set Difference in list of dictionaries The difference of two lists have been discussed many times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension The na
3 min read
Python | Difference in keys of two dictionaries In this article, we will be given two dictionaries dic1 and dic2 which may contain the same keys and we have to find the difference of keys in the given dictionaries using Python. Example Input: dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}, dict2= {'key1':'Geeks', 'key2':'Portal'} Output: k
5 min read
Python | Find Symmetric Pairs in dictionary Sometimes, while working with Python dictionary, one can have a problem in which one desires to get key-value pairs that are symmetrical, i.e that has key-value pair of same value irrespective of the fact value is a key or value. Let's discuss certain ways in which this task can be performed. Method
6 min read
Python - Sort Dictionary by Value Difference Sometimes, while working with Python dictionaries, we can have problem in which in which we need to perform sorting of items on basis of various factors. One such can be on basis of absolute difference of dual value list. This can occur in Python > 3.6, as dictionaries are ordered. This kind of p
3 min read
Python | Subtraction of dictionaries Sometimes, while working with dictionaries, we might have a utility problem in which we need to perform elementary operations among the common keys of dictionaries in Python. This can be extended to any operation to be performed. Let's discuss the subtraction of like key values and ways to solve it
6 min read
Python - Symmetric Difference of Multiple sets Symmetric Differences among groups of sets are elements that belong to any one of the sets but are not present in any other set. Given a list of sets and the task is to write a Python program to get the symmetric difference of the same. Input : test_list = [{5, 3, 2, 6, 1}, {7, 5, 3, 8, 2}, {9, 3},
3 min read