Python program to extract key-value pairs with substring in a dictionary


Dictionaries in python are data structures that store data in the form of key-value pairs. Each key is unique and it is associated with different values. A dictionary helps us to access and retrieve data efficiently allowing a programmer to build an optimized code. Specific key-value pairs can be extracted from a given dictionary based on different requirements.

This selective item extraction helps us to produce a dictionary consisting of relevant information. In this article, we will be discussing a similar concept of item extraction from a dictionary based on a reference “substring”.

Understanding the Problem

We will create a dictionary consisting of different keys and their corresponding values and then pass a substring. We have to extract those key-value pairs which contains this substring. Let’s understand this with the help of an example: -

Input Output Scenarios

Let us consider a dictionary with the following values −

Input: dict1 = {"Marks": [36, 45, 68], "Grades":["F", "C+", "B+"], "Remarks": "Satisfactory result", "Day": "Saturday"}
substring = "Sat"

As we can see, the substring passed here is “Sat”. So, the dictionary items containing this substring must be retrieved. The following key-value pairs are returned.

Output: {'Remarks': 'Satisfactory result', 'Day': 'Saturday'}

Now that we have understood the problems statement, let’s discuss a few solutions.

Operating on a Single Dictionary using Iterations (loops)

We will pass a substring named along with a dictionary. An empty dictionary will be created which will store the extracted key-value pairs. After this, we will iterate over the original dictionary and establish a condition for isolating those values that contains the substring with the help of “if” statement. The values will have checked with the help of “in” operator.

Example

Following is an example to extract key-value pairs with substring in a dictionary −

dict1 = {"Marks": [36, 45, 68], "Grades":["F", "C+", "B+"], "Remarks": "Satisfactory result", "Day": "Saturday"}
substring = "Sat"
dict2 = {}

for keys, values in dict1.items():
   if substring in values:
      dict2[keys] = values

print(dict2) 

Output

{'Remarks': 'Satisfactory result', 'Day': 'Saturday'}

Operating on a List of Dictionaries using Iterations (loops)

Here we will use the same technique of iterations for extracting the key-value pairs but instead of operating on a single dictionary we will consider a list of dictionaries and isolate the appropriate dictionaries not just single key-value pairs. These dictionaries will be returned in a list.

Example

Following is an example −

lisDict = [{"Name": "Manish Sinah"}, {"Name": "Raghav Kapoor"}, {"Name": "Raghu Pandey"}, {"Name": "Khushi Agarwal"}]
substring = "Rag"
lis2 = []
key = "Name"

for Dict in lisDict:
   if substring in Dict[key]:
      lis2.append(Dict)

print(lis2)

Output

[{'Name': 'Raghav Kapoor'}, {'Name': 'Raghu Pandey'}]

As we can see the two dictionaries containing the substring “Rag” were returned.

Using List Comprehension

This is an elegant and compact technique of extracting the key-value pairs. A single line of code will summarize the multiline iterations and a list of relevant dictionaries shall be returned.

Example

Following is an example −

LisDict = [{"Name": "Manish Sinah"}, {"Name": "Raghav Kapoor"}, {"Name": "Raghu Pandey"}, {"Name": "Khushi Agarwal"}]
substring = "Rag"
key = "Name"

lis2 = [Dict for Dict in LisDict if substring in Dict[key]]
print(lis2)

Output

[{'Name': 'Raghav Kapoor'}, {'Name': 'Raghu Pandey'}]

Using Filter() and Lambda functions

In this approach, we will use the “filter()” function to filter those dictionaries which contains the substring in their values. The filtering condition is set up by the lambda function.

The lambda function will retrieve the values associated with the passed “key” as well as check whether or not the substring is present in that “value”. The lambda function returns either “True” or “False” depending upon the values encountered and based on this Boolean result, an item is either included or filtered out.

Example

Following is an example −

lisDict = [{"Name": "Manish Sinah"}, {"Name": "Raghav Kapoor"}, {"Name": "Raghu Pandey"}, {"Name": "Khushi Agarwal"}]
substring = "Rag"
key = "Name"

Fil_lis = list(filter(lambda item: substring in item[key], lisDict))
print(Fil_lis)

Output

[{'Name': 'Raghav Kapoor'}, {'Name': 'Raghu Pandey'}]

Alternative Solution and Other Insights

An alternative solution for extracting the key-value pairs with substring includes the use of “map()” function along with the lambda function. The map function will help us to iterate over the dictionaries and the lambda function will check for the values containing the substring.

The “type error” is a common error that can be encountered while handling these dictionaries. Make sure the dictionaries values are iterable so that can be compared and traversed properly.

Conclusion

During the course of this article, we discussed the different solutions to extract key-value pairs with substring in a dictionary. Initially we focused on the explanation of the problem and then we jumped onto the solutions. We discussed the concept of iteration as the primary solution. After that, we understood the techniques like: list comprehension and filter() function and used them to extract the key-value pairs.

Updated on: 12-Jul-2023

574 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements