Reputation:
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'}
Upvotes: 0
Views: 141
Reputation: 399863
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.
Upvotes: 0
Reputation: 5613
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)
.
Upvotes: 1
Reputation: 212895
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.
Upvotes: 3