简体   繁体   中英

Python: Modifying a Function to Search Values in a Dictionary

I wrote a simple function that receives a dictionary and a string as a parameter. The function uses the string to search the dictionary and then returns a new dictionary with results.

Now i need some help modifying this code, or creating a new function, that when passed a string, searches values, in the key:value pair, as opposed to only the keys. So if I pass '1' as a parameter I get a new dictionary which includes cat.

Hopefully this is clear. Thanks in advance.

a = {'rainbows': 'xbox', 'solider': 'miltary', 'cat': 1}

def searchKeys(aDictionary,searchTerm):
    results = {}

    for i in aDictionary:
        if searchTerm in i:
            results[i] = aDictionary[i]
    return results

###searchKeys(a,'r') -> {'rainbows': 'xbox', 'solider': 'miltary'}
def searchKeys(aDictionary,searchTerm):
    results = {}

    for k,v in aDictionary.iteritems():
        if searchTerm in k or searchTerm in v:
            results[k] = v
    return results

or shorter:

results = dict((k,v) for k,v in a.iteritems() if searchItem in k or searchItem in v)

It will however not work with your example dictionary, because 1 (value for cat ) is not a string and therefore cannot contain another string.

With Python 2.7, this is the most simple solution:

def searchItems(aDictionary, searchTerm):
    return {k:v for k, v in aDictionary.iteritems()
        if searchTerm in k or searchTerm in str(v)}

Or, if you are sure that all values are strings, you can just write in v instead of in str(v) .

Well, once you have a key i , the value for that key is aDictionary[i] , so just extend your testing.

There are more optimal ways of doing this, that don't do the look-up as explicitly, but the above is straight-forward and easy to understand, and should be fine for many cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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