[python] How to search if dictionary value contains certain string with Python

I have a dictionary with key-value pair. My value contains strings. How can I search if a specific string exists in the dictionary and return the key that correspond to the key that contains the value.

Let's say I want to search if the string 'Mary' exists in the dictionary value and get the key that contains it. This is what I tried but obviously it doesn't work that way.

#Just an example how the dictionary may look like
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
          'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

#Checking if string 'Mary' exists in dictionary value
print 'Mary' in myDict.values()

Is there a better way to do this since I may want to look for a substring of the value stored ('Mary' is a substring of the value 'Mary-Ann').

This question is related to python string dictionary key-value

The answer is


>>> myDict
{'lastName': ['Stone', 'Lee'], 'age': ['12'], 'firstName': ['Alan', 'Mary-Ann'],
 'address': ['34 Main Street, 212 First Avenue']}

>>> Set = set()

>>> not ['' for Key, Values in myDict.items() for Value in Values if 'Mary' in Value and Set.add(Key)] and list(Set)
['firstName']

import re
for i in range(len(myDict.values())):
    for j in range(len(myDict.values()[i])):
         match=re.search(r'Mary', myDict.values()[i][j])
         if match:
                 print match.group() #Mary
                 print myDict.keys()[i] #firstName
                 print myDict.values()[i][j] #Mary-Ann

Following is one liner for accepted answer ... (for one line lovers ..)

def search_dict(my_dict,searchFor):
    s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]    
    return s_val

I am a bit late, but another way is to use list comprehension and the any function, that takes an iterable and returns True whenever one element is True :

# Checking if string 'Mary' exists in the lists of the dictionary values
print any(any('Mary' in s for s in subList) for subList in myDict.values())

If you wanna count the number of element that have "Mary" in them, you can use sum():

# Number of sublists containing 'Mary'
print sum(any('Mary' in s for s in subList) for subList in myDict.values())

# Number of strings containing 'Mary'
print sum(sum('Mary' in s for s in subList) for subList in myDict.values())

From these methods, we can easily make functions to check which are the keys or values matching.

To get the keys containing 'Mary':

def matchingKeys(dictionary, searchString):
    return [key for key,val in dictionary.items() if any(searchString in s for s in val)]

To get the sublists:

def matchingValues(dictionary, searchString):
    return [val for val in dictionary.values() if any(searchString in s for s in val)]

To get the strings:

def matchingValues(dictionary, searchString):
    return [s for s i for val in dictionary.values() if any(searchString in s for s in val)]

To get both:

def matchingElements(dictionary, searchString):
    return {key:val for key,val in dictionary.items() if any(searchString in s for s in val)}

And if you want to get only the strings containing "Mary", you can do a double list comprehension :

def matchingStrings(dictionary, searchString):
    return [s for val in dictionary.values() for s in val if searchString in s]

Klaus solution has less overhead, on the other hand this one may be more readable

myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
          'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}

def search(myDict, lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return key

search(myDict, 'Mary')

import json 'mtach' in json.dumps(myDict) is true if found


For me, this also worked:

def search(myDict, search1):
    search.a=[]
    for key, value in myDict.items():
        if search1 in value:
            search.a.append(key)

search(myDict, 'anyName')
print(search.a)
  • search.a makes the list a globally available
  • if a match of the substring is found in any value, the key of that value will be appended to a

def search(myDict, lookup):
    a=[]
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                 a.append(key)
    a=list(set(a))
    return a

if the research involves more keys maybe you should create a list with all the keys


import re
for i in range(len(myDict.values())):
     for j in range(len(myDict.values()[i])):
             match=re.search(r'Mary', myDict.values()[i][j])
             if match:
                     print match.group() #Mary
                     print myDict.keys()[i] #firstName
                     print myDict.values()[i][j] #Mary-Ann

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to key-value

Iterate through dictionary values? How can I get key's value from dictionary in Swift? How to add a new object (key-value pair) to an array in javascript? How to search if dictionary value contains certain string with Python Python: How to check if keys exists and retrieve value from Dictionary in descending priority How do you create a dictionary in Java? how to prevent adding duplicate keys to a javascript array How to update value of a key in dictionary in c#? How to create dictionary and add key–value pairs dynamically? How to count frequency of characters in a string?