Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 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 contain this substring. Let's understand this with the help of an example ?
Input Output Scenarios
Let us consider a dictionary with the following values ?
dict1 = {"Marks": [36, 45, 68], "Grades":["F", "C+", "B+"], "Remarks": "Satisfactory result", "Day": "Saturday"}
substring = "Sat"
print("Original Dictionary:", dict1)
print("Substring to search:", substring)
Original Dictionary: {'Marks': [36, 45, 68], 'Grades': ['F', 'C+', 'B+'], 'Remarks': 'Satisfactory result', 'Day': 'Saturday'}
Substring to search: 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 ?
# Expected output for the above example
result = {'Remarks': 'Satisfactory result', 'Day': 'Saturday'}
print("Expected Output:", result)
Expected Output: {'Remarks': 'Satisfactory result', 'Day': 'Saturday'}
Using Dictionary Iteration
We will pass a substring 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 contain the substring with the help of if statement. The values will be checked with the help of in operator ?
dict1 = {"Marks": [36, 45, 68], "Grades":["F", "C+", "B+"], "Remarks": "Satisfactory result", "Day": "Saturday"}
substring = "Sat"
result_dict = {}
for key, value in dict1.items():
# Check if the value is a string and contains substring
if isinstance(value, str) and substring in value:
result_dict[key] = value
print("Filtered Dictionary:", result_dict)
Filtered Dictionary: {'Remarks': 'Satisfactory result', 'Day': 'Saturday'}
Using Dictionary Comprehension
Dictionary comprehension provides a more elegant and compact way to extract key-value pairs. This approach creates a new dictionary in a single line of code ?
dict1 = {"Marks": [36, 45, 68], "Grades":["F", "C+", "B+"], "Remarks": "Satisfactory result", "Day": "Saturday"}
substring = "Sat"
result_dict = {key: value for key, value in dict1.items()
if isinstance(value, str) and substring in value}
print("Filtered Dictionary:", result_dict)
Filtered Dictionary: {'Remarks': 'Satisfactory result', 'Day': 'Saturday'}
Operating on List of Dictionaries
Here we will use the same technique for extracting key-value pairs but instead of operating on a single dictionary, we will consider a list of dictionaries and isolate the appropriate dictionaries containing the substring ?
students = [{"Name": "Manish Sinah"}, {"Name": "Raghav Kapoor"}, {"Name": "Raghu Pandey"}, {"Name": "Khushi Agarwal"}]
substring = "Rag"
filtered_students = []
key_to_search = "Name"
for student in students:
if substring in student[key_to_search]:
filtered_students.append(student)
print("Filtered Students:", filtered_students)
Filtered Students: [{'Name': 'Raghav Kapoor'}, {'Name': 'Raghu Pandey'}]
Using List Comprehension for Multiple Dictionaries
This is an elegant and compact technique of extracting dictionaries from a list. A single line of code will summarize the multiline iterations and return a list of relevant dictionaries ?
students = [{"Name": "Manish Sinah"}, {"Name": "Raghav Kapoor"}, {"Name": "Raghu Pandey"}, {"Name": "Khushi Agarwal"}]
substring = "Rag"
key_to_search = "Name"
filtered_students = [student for student in students if substring in student[key_to_search]]
print("Filtered Students:", filtered_students)
Filtered Students: [{'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 contain the substring in their values. The filtering condition is set up by the lambda function ?
students = [{"Name": "Manish Sinah"}, {"Name": "Raghav Kapoor"}, {"Name": "Raghu Pandey"}, {"Name": "Khushi Agarwal"}]
substring = "Rag"
key_to_search = "Name"
filtered_students = list(filter(lambda student: substring in student[key_to_search], students))
print("Filtered Students:", filtered_students)
Filtered Students: [{'Name': 'Raghav Kapoor'}, {'Name': 'Raghu Pandey'}]
Comparison of Methods
| Method | Best For | Readability | Performance |
|---|---|---|---|
| Dictionary Iteration | Beginners | High | Good |
| Dictionary Comprehension | Single dictionaries | High | Best |
| List Comprehension | Multiple dictionaries | High | Best |
| Filter + Lambda | Functional programming | Medium | Good |
Conclusion
Dictionary comprehension provides the most efficient and readable solution for extracting key-value pairs with substrings. Use list comprehension when working with multiple dictionaries, and consider filter() with lambda for functional programming approaches.
