简体   繁体   English

如何使用 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.假设我想搜索字典值中是否存在字符串 'Mary' 并获取包含它的键。 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').有没有更好的方法来做到这一点,因为我可能想查找存储值的子字符串('Mary' 是值 'Mary-Ann' 的子字符串)。

You can do it like this:你可以这样做:

#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']}

def search(values, searchFor):
    for k in values:
        for v in values[k]:
            if searchFor in v:
                return k
    return None

#Checking if string 'Mary' exists in dictionary value
print search(myDict, 'Mary') #prints firstName

Klaus solution has less overhead, on the other hand this one may be more readable Klaus 解决方案的开销较少,另一方面,这个解决方案可能更具可读性

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')

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 :我有点晚,但另一种方法是使用列表理解和any功能,这需要一个迭代,并返回True每当一个元素是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() :如果您想计算其中包含“玛丽”的元素数量,可以使用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 :如果您只想获取包含“Mary”的字符串,您可以进行双重列表理解:

def matchingStrings(dictionary, searchString):
    return [s for val in dictionary.values() for s in val if searchString in s]
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
>>> 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']

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 search.a 使列表全局可用
  • if a match of the substring is found in any value, the key of that value will be appended to a如果在任何值中找到子字符串的匹配项,则该值的键将附加到

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
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
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如果研究涉及更多密钥,也许您应该创建一个包含所有密钥的列表

To provide a more general solution for others using this post to do similar or more complex python dictionary searches: you can use dictpy为使用这篇文章进行类似或更复杂的 Python 字典搜索的其他人提供更通用的解决方案:您可以使用dictpy

import dictpy

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

search = dictpy.DictSearch(data=myDict, target='Mary-Ann')
print(search.result)   # prints -> [firstName.1, 'Mary-Ann']  

The first entry in the list is the target location: dictionary key "firstName" and position 1 in the list.列表中的第一个条目是目标位置:字典键“firstName”和列表中的位置 1。 The second entry is the search return object.第二个条目是搜索返回对象。

The benefit of dictpy is it can find multiple 'Mary-Ann' and not just the first one. dictpy的好处是它可以找到多个 'Mary-Ann' 而不仅仅是第一个。 It tells you the location in which it found it, and you can search more complex dictionaries (more levels of nesting) and change what the return object is.它会告诉您找到它的位置,您可以搜索更复杂的字典(更多级别的嵌套)并更改返回对象的内容。

如果找到,在 json.dumps(myDict) 中导入 json 'mtach' 为真

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM