本文介绍了如何搜索字典值包含某些字符串与Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个带键值对的字典。我的值包含字符串。如何搜索字典中是否存在特定的字符串,并返回与包含该值的键对应的键。 我想搜索如果字符串'Mary'存在于字典值中,并获取包含它的键。这是我尝试的,但显然它不会这样工作。 #这个例子如何字典看起来像 myDict = {'age':['12'],'address':['34 Main Street,212 First Avenue'],'firstName':['Alan','Mary-Ann' ],'lastName':['Stone','Lee']} #检查字符串'Mary'是否存在于字典值 print'Mary'in myDict.values()$有没有更好的方法来做这个,因为我可能想要寻找一个存储的值的子字符串($)$ / pre 解决方案你可以这样做: p> #这是一个例子,字典如何看起来像 myDict = {'age':['12'],'地址':['34 Main Street,212 First Avenue'],'firstName':['Alan','Mary-Ann'],'lastName':['Stone','Lee']} def se arch(values,searchFor): for k in values: for v in values [k]: if searchFor in v: return k return None #检查字符串'Mary'是否存在于字典值中 print search(myDict,'Mary')#prints firstName 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 likemyDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'], 'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}#Checking if string 'Mary' exists in dictionary valueprint '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'). 解决方案 You can do it like this:#Just an example how the dictionary may look likemyDict = {'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 valueprint search(myDict, 'Mary') #prints firstName 这篇关于如何搜索字典值包含某些字符串与Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-23 14:03