如何使用 Python 搜索字典值是否包含某个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17340922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:57:50  来源:igfitidea点击:

How to search if dictionary value contains certain string with Python

pythonstringdictionarykey-value

提问by Cryssie

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.

假设我想搜索字典值中是否存在字符串 'Mary' 并获取包含它的键。这是我尝试过的,但显然它不能那样工作。

#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' 的子字符串)。

采纳答案by Klaus Byskov Pedersen

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

回答by thefourtheye

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

回答by Moh Zah

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

回答by rash

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

回答by rash

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

回答by Armando Sodano

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

如果研究涉及更多密钥,也许您应该创建一个包含所有密钥的列表

回答by Shushiro

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
  • search.a 使列表全局可用
  • 如果在任何值中找到子字符串的匹配项,则该值的键将附加到

回答by shantanu pathak

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

回答by Amer

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

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

回答by Nei

I am a bit late, but another way is to use list comprehension and check the length of the result :

我有点晚了,但另一种方法是使用列表理解并检查结果的长度:

#Checking if string 'Mary' exists in dictionary value
print len([val for key,val in myDict if 'Mary' in val]) > 0

Here, I actually make a list of each value containing 'Mary'and check it I have some. We can also use sum():

在这里,我实际上列出了每个包含的值'Mary'并检查它我有一些。我们还可以使用sum()

#Checking if string 'Mary' exists in dictionary value
print sum(1 for key,val in myDict if 'Mary' in val) > 0

This second method is optimized since it doesn't store the list before computing the length. (The difference is significant on a big number of elements, but here you should not see any important difference)

第二种方法经过优化,因为它在计算长度之前不存储列表。(在大量元素上差异显着,但在这里您应该看不到任何重要差异)

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

从这些方法中,我们可以轻松地创建函数来检查哪些键或值匹配。

To get the keys:

获取密钥:

def matchingKeys(dictionnary, searchString):
    return [key for key,val in myDict if 'Mary' in val]

To get the values:

要获取值:

def matchingValues(dictionnary, searchString):
    return [val for key,val in myDict if 'Mary' in val]

To get both:

要同时获得:

def matchingElements(dictionnary, searchString):
    return {key:val for key,val in myDict if 'Mary' in val}

To just get the number of elements:

只获取元素的数量:

def matchingElements(dictionnary, searchString):
    return sum(1 for key,val in myDict if 'Mary' in val)

And that's it. Hope I helped someone getting some ideas !!

就是这样。希望我能帮助某人获得一些想法!