GeeksforGeeks App
Open App
Browser
Continue

# Python – Extract Similar Key Values

Given a dictionary, extract all values which are from similar keys, i.e contains all similar characters, just jumbled to form each other.

Input : test_dict = {'gfg' : 5, 'ggf' : 19, 'gffg' : 9, 'gff' : 3, 'fgg' : 3}, tst_wrd = 'fgg'
Output : [5, 19, 3]
Explanation : gfg, ggf and fgg have values, 5, 19 and 3.
Input : test_dict = {'gfg' : 5, 'gffg' : 9, 'gff' : 3, 'fgg' : 3}, tst_wrd = 'fgg'
Output : [5, 3]
Explanation : gfg and fgg have values, 5 and 3.

Method #1 : Using sorted() + loop

In this, we compare the key after sorting with the target key, will have similar elements in the correct order, and can be checked for equality. Once with match, their values are extracted.

## Python3

 # Python3 code to demonstrate working of# Extract Similar Key Values# Using loop + sorted() # initializing dictionarytest_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing wordtst_wrd = 'fgg' res = []for key, val in test_dict.items():     # sorted to get similar key order    if ''.join(list(sorted(key))) == tst_wrd:        res.append(val) # printing resultprint("The extracted keys : " + str(res))

Output

The original dictionary is : {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
The extracted keys : [5, 19, 3]

Time Complexity: O(n), where n is the length of the list test_dict
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 list comprehension + sorted()

In this, we perform a similar task as above, just perform using shorthand using sorted() and list comprehension.

## Python3

 # Python3 code to demonstrate working of# Extract Similar Key Values# Using list comprehension + sorted() # initializing dictionarytest_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing wordtst_wrd = 'fgg' # one-liner to solve thisres = [val for key, val in test_dict.items() if ''.join(list(sorted(key))) == tst_wrd] # printing resultprint("The extracted keys : " + str(res))

Output

The original dictionary is : {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
The extracted keys : [5, 19, 3]

Method 3:  using a dictionary comprehension.

Here is the step-by-step approach:

• Initialize an empty dictionary called result_dict to store the matched key-value pairs.
• Loop through each key-value pair in the input dictionary test_dict.
• Sort the characters in the current key using sorted() function and join them back into a string.
• If the sorted key matches the given word tst_wrd, add the key-value pair to result_dict.
• Return the values from result_dict as a list.

Example:

## Python3

 # Python3 code to demonstrate working of# Extract Similar Key Values# Using dictionary comprehension + sorted() # initializing dictionarytest_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing wordtst_wrd = 'fgg' # initializing an empty dictionary to store the matched key-value pairsresult_dict = {} # loop through each key-value pair in test_dictfor key, value in test_dict.items():     # sort the characters in the current key and join them back into a string    sorted_key = ''.join(sorted(key))     # check if the sorted key matches the given word    if sorted_key == tst_wrd:        # add the key-value pair to result_dict        result_dict[key] = value # get the values from result_dict as a listres = list(result_dict.values()) # printing resultprint("The extracted values : " + str(res))

Output

The original dictionary is : {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
The extracted values : [5, 19, 3]

Time Complexity: O(n * klog(k)) where n is the number of key-value pairs in the input dictionary and k is the maximum length of any key. This is because we are sorting each key which takes klog(k) time, and we do this for n keys.
Auxiliary Space: O(n) as we are storing the matched key-value pairs in the result_dict which can have up to n entries.

Method #4: Using filter() and lambda function

Algorithm:

1. Initializes a dictionary named test_dict.
2. Prints the original dictionary.
3. The filter() function with a lambda function to get the values from the test_dict dictionary whose sorted keys match the value of tst_wrd.
4. The items() method is used to get the key-value pairs of the dictionary, and join() and sorted() functions are used to sort the keys and join them into a single string, respectively.
5. The filter() function converts into a list using the list() function and assigns it to the variable ‘res’.

## Python3

 # initializing dictionarytest_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing wordtst_wrd = 'fgg' # using filter() and a lambda function to get the values matching the sorted wordres = list(filter(lambda x: ''.join(    sorted(x[0])) == tst_wrd, test_dict.items())) # extracting the values from the resultres = [val for _, val in res] # printing resultprint("The extracted values : " + str(res))

Output

The original dictionary is : {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
The extracted values : [5, 19, 3]

Time Complexity: O(N*log(N)) where n is the length of the dictionary and sorting the characters in each key, which takes O(logn) time. \

Auxiliary Space: O(N) where N is the number of keys in the dictionary

My Personal Notes arrow_drop_up