Python – Remove Dictionaries with Matching Values

PythonServer Side ProgrammingProgramming

When it is required to remove dictionaries with matching values, a dictionary comprehension is used.

Below is a demonstration of the same −

Example

 Live Demo

my_dict_1 = [{'Hi': 32, "there": 32, "Will":19},{'Hi': 19, "there": 100, "Will": 13}, {'Hi': 72, "there": 19, "Will": 72}]

print("The first dictionary is : ")
print(my_dict_1)

my_dict_2 = [{'Hi': 72, "Will": 19}, {"Will": 13, "Hi": 19}]
print("The second dictionary is : ")
print(my_dict_2)

K = "Hi"
print("The value of K is ")
print(K)

temp = { element[K] for element in my_dict_2}

my_result = [element for element in my_dict_1 if element[K] not in temp]

print("The result is : " )
print(my_result)

Output

The first dictionary is :
[{'Hi': 32, 'there': 32, 'Will': 19}, {'Hi': 19, 'there': 100, 'Will': 13}, {'Hi': 72, 'there': 19, 'Will': 72}]
The second dictionary is :
[{'Hi': 72, 'Will': 19}, {'Will': 13, 'Hi': 19}]
The value of K is
Hi
The result is :
[{'Hi': 32, 'there': 32, 'Will': 19}]

Explanation

  • Two dictionaries are defined and is displayed on the console.

  • A value for K is defined and displayed on console.

  • The second dictionary is iterated over, and elements are checked with K and stored in a temporary variable ‘temp’.

  • The first dictionary is iterated over, and elements in it are checked with the temporary variable ‘temp’ and assigned to a variable.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 06-Sep-2021 07:11:08
Advertisements