Python - Extract Similar Key Values
Last Updated :
27 Apr, 2023
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 dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_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 result
print("The extracted keys : " + str(res))
OutputThe 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 dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_wrd = 'fgg'
# one-liner to solve this
res = [val for key, val in test_dict.items(
) if ''.join(list(sorted(key))) == tst_wrd]
# printing result
print("The extracted keys : " + str(res))
OutputThe 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 dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_wrd = 'fgg'
# initializing an empty dictionary to store the matched key-value pairs
result_dict = {}
# loop through each key-value pair in test_dict
for 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 list
res = list(result_dict.values())
# printing result
print("The extracted values : " + str(res))
OutputThe 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:
- Initializes a dictionary named test_dict.
- Prints the original dictionary.
- 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.
- 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.
- The filter() function converts into a list using the list() function and assigns it to the variable 'res'.
Python3
# initializing dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_wrd = 'fgg'
# using filter() and a lambda function to get the values matching the sorted word
res = list(filter(lambda x: ''.join(
sorted(x[0])) == tst_wrd, test_dict.items()))
# extracting the values from the result
res = [val for _, val in res]
# printing result
print("The extracted values : " + str(res))
OutputThe 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
Similar Reads
Python - Append Similar Values as Key Sometimes, while working with data, we can have problems in which we need to categorize a particular list and values to similar keys. This can be a problem in counting data. Like counting votes or counting coins. Let's discuss certain ways in which this task can be performed. Method #1: Using loop T
7 min read
Get specific keys' values - Python Our task is to retrieve values associated with specific keys from a dictionary. This is especially useful when we only need to access certain pieces of data rather than the entire dictionary. For example, suppose we have the following dictionary: d = {'name': 'John', 'age': 25, 'location': 'New York
3 min read
Python - Extract Unique value key pairs Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in wh
5 min read
Python - Extract Keys with specific Value Type Given a dictionary, extract all the keys, whose values are of a given type. Input : test_dict = {'gfg' : 2, 'is' : 'hello', 'for' : {'1' : 3}, 'geeks' : 4}, targ_type = int Output : ['gfg', 'geeks'] Explanation : gfg and geeks have integer values. Input : test_dict = {'gfg' : 2, 'is' : 'hello', 'for
7 min read
Python | Search Key from Value The problem of finding a value from a given key is quite common. But we may have a problem in which we wish to get the back key from the input key we feed. Let's discuss certain ways in which this problem can be solved. Method #1 : Using Naive Method In this method, we just run a loop for each of th
4 min read
Python - Extracting Key from Value Substring Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the key from given value, querying substring from key's value. This kind of problem is common and have application in many domains including web development. Lets discuss certain ways in which this task
5 min read
Python | Extract similar index elements Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are having similar index values. This kind of problem can come in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loo
6 min read
Python - Convert Lists into Similar key value lists Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corre
12 min read
Python - Concatenate all keys which have similar values Given a dictionary with string keys and sets as values the task is to write a python program to concatenate keys all of which have similar values order irrespective. Input : test_dict = {'gfg' : {5, 4, 3}, 'is' : {4, 3, 5}, 'best' : {1, 4, 3}, 'for' : {1, 3, 4}, 'geeks' : {1, 2, 3}} Output : {'gfg-i
8 min read