Check If Dictionary Value Contains Certain String with Python
Last Updated :
05 Feb, 2025
We need to check if the value associated with a key in a dictionary contains a specific substring. For example, if we have a dictionary of user profiles and we want to check if any user’s description contains a particular word, we can do this easily using various methods. Let’s look at a few ways to check if dictionary values contain a certain string.
Using 'in' operator
This method checks if a substring is present in the value using Python's built-in 'in' operator, which is efficient and simple to use.
Python
a = {'user1': 'loves python', 'user2': 'enjoys reading', 'user3': 'python is fun'}
# Substring to check
b = 'python'
# Checking if the value contains the substring
c = {k: v for k, v in a.items() if b in v}
print(c)
Output{'user1': 'loves python', 'user3': 'python is fun'}
Explanation:
- We use a dictionary comprehension to iterate over each key-value pair in the dictionary.
- The in operator checks if the specified substring is present in the value.
- If the substring is found, the key-value pair is included in the result.
Let's explore some more ways and see how we can check if dictionary value contains certain string with Python.
Using str.find()
find() method returns the index of the first occurrence of a substring in a string. If the substring is not found, it returns -1. This method can be used to check if a string contains a specific word.
Python
a = {'user1': 'loves python', 'user2': 'enjoys reading', 'user3': 'python is fun'}
# Substring to check
b = 'python'
# Checking if the value contains the substring using find()
c = {k: v for k, v in a.items() if v.find(b) != -1}
print(c)
Output{'user1': 'loves python', 'user3': 'python is fun'}
Explanation:
- The find() method is used to search for the substring within the value.
- If the substring is not found, find() returns -1, so we check if the result is not -1 to include the pair in the result.
- This method works similarly to the in operator but allows more flexibility if you need to work with the position of the substring.
Using str.__contains__()
This method is essentially the same as the in operator but uses the str.__contains__() special method, which checks if a substring exists in the string.
Python
a = {'user1': 'loves python', 'user2': 'enjoys reading', 'user3': 'python is fun'}
# Substring to check
b = 'python'
# Checking if the value contains the substring using __contains__()
c = {k: v for k, v in a.items() if v.__contains__(b)}
print(c)
Output{'user1': 'loves python', 'user3': 'python is fun'}
Explanation:
- The __contains__() method checks if the given substring is found in the string.
- If the substring is present, it returns True, and the key-value pair is included in the result.
- This method is more explicit than using the in operator but the in operator is generally preferred due to its simplicity.
Using filter() with lambda function
This method uses the filter() function along with a lambda function to check if the value contains the substring.
Python
a = {'user1': 'loves python', 'user2': 'enjoys reading', 'user3': 'python is fun'}
# Substring to check
b = 'python'
# Using filter() with a lambda to check the condition
c = dict(filter(lambda x: b in x[1], a.items()))
print(c)
Output{'user1': 'loves python', 'user3': 'python is fun'}
Explanation:
- filter() function filters out items that do not meet the condition.
- lambda function checks if the substring is present in the value.
Using regular expressions (re module)
If the substring is more complex or needs to match a pattern, regular expressions can be used. This method allows for advanced string searching capabilities.
Python
import re
a = {'user1': 'loves python', 'user2': 'enjoys reading', 'user3': 'python is fun'}
# Substring to check
b = 'python'
# Using re.search() to check if the value contains the substring
c = {k: v for k, v in a.items() if re.search(b, v)}
print(c)
Output{'user1': 'loves python', 'user3': 'python is fun'}
Explanation:
- re.search() method searches for the substring (or pattern) in the string.
- If the substring is found, re.search() returns a match object, which is considered True in a boolean context.
Similar Reads
Python | Test if dictionary contains unique keys and values Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required
6 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
Python - Keys associated with value list in dictionary Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
4 min read
How to check if a Python variable exists? Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Letâs explore different methods to efficiently check if a va
3 min read
Dynamic Testing of Values Against Python Literal Types In Python, Literal types are a way to specify that a value must be one of a set of specific values. This can be useful for type checking and ensuring your code handles only expected values. However, dynamically testing whether a value conforms to a Literal type can be tricky. This article will guide
4 min read
How to check multiple variables against a value in Python? Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python: Method #1: Using or operator This is pretty simple and straightforward. The following code snippets illustrate this method. Example
2 min read
How to Check if a Pandas Column Has a Value from a List of Strings? A "list of strings" refers to a list where each element is a string, and our goal is to determine whether the values in a specific column of the DataFrame are present in that list. Let's learn how to check if a Pandas DataFrame column contains any value from a list of strings in Python.Checking Pand
4 min read
Python - Check if substring present in string The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis
2 min read
Python | Check if given multiple keys exist in a dictionary A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice"
3 min read
Python - Access Dictionary items A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets.Example:Pythona = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value assosiated with "geeks" x = a["geeks"] print
3 min read