Python – Extract Equal Pair Dictionary
While working with a Python dictionary, we are supppsed to create a new dictionary of the existing dictionary having tuple as key. We desire to create a singleton key dictionary with keys only where both elements of pair are equal. This can have applications in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1: Using loop
This is a brute way in which this task can be performed. In this, we iterate for each element of tuple dictionary and compare for equality to create new dictionary.
Python3
# Python3 code to demonstrate working of # Extract Equal Pair Dictionary # Using loop # initializing dictionary test_dict = {( 1 , 1 ): 4 , ( 2 , 3 ): 6 , ( 3 , 3 ): 7 , ( 5 , 2 ): 10 , ( 2 , 2 ): 11 } # printing original dictionary print (& quot The original dictionary is : & quot + str (test_dict)) # Extract Equal Pair Dictionary # Using loops res = dict () for key, val in test_dict.items(): if key[ 0 ] = = key[ 1 ]: res[key[ 0 ]] = val # printing result print (& quot The dictionary after equality testing : & quot + str (res)) |
Output : The original dictionary is : {(5, 2): 10, (2, 2): 11, (2, 3): 6, (1, 1): 4, (3, 3): 7} The dictionary after equality testing : {1: 4, 2: 11, 3: 7}
Method #2 : Using dictionary comprehension:
This is yet another way in which this task can be performed. In this, we use dictionary comprehension instead of the loop to provide shorthand.
Python3
# Python3 code to demonstrate working of # Extract Equal Pair Dictionary # Using dictionary comprehension # initializing dictionary test_dict = {( 1 , 1 ): 4 , ( 2 , 3 ): 6 , ( 3 , 3 ): 7 , ( 5 , 2 ): 10 , ( 2 , 2 ): 11 } # printing original dictionary print (& quot The original dictionary is : & quot + str (test_dict)) # Extract Equal Pair Dictionary # Using dictionary comprehension res = {idx[ 0 ]: j for idx, j in test_dict.items() if idx[ 0 ] = = idx[ 1 ]} # printing result print (& quot The dictionary after equality testing : & quot + str (res)) |
Output : The original dictionary is : {(5, 2): 10, (2, 2): 11, (2, 3): 6, (1, 1): 4, (3, 3): 7} The dictionary after equality testing : {1: 4, 2: 11, 3: 7}