如何搜索字典值包含某些字符串与Python [英] How to search if dictionary value contains certain string with Python

查看:747
本文介绍了如何搜索字典值包含某些字符串与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

< 'Mary'是值Mary-Ann的子串。

解决方案

你可以这样做: 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 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').

解决方案

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

这篇关于如何搜索字典值包含某些字符串与Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆