There are at least two ways to accomplish your goal. In Example A, a quick query is run to determine if your member is part of your hash. It stops as soon as a match is found. On the other hand, Example B may prove to be more useful since all matching values are returned. This allows you to process that part of the hash dealing with your member without having to run another query.
#! /usr/bin/env python3
def main():
"""Demonstrate the usage of dict_contains and dict_search."""
my_list = ['ist', 'out', 'ear', 'loopy']
my_hash = {'a': 50, 'across': 14, 'ahash': 12, 'alist': 31, 'an': 73,
'and': 11, 'are': 2, 'as': 34, 'avoid': 82, 'be': 3,
'besides': 49, 'but': 45, 'can': 32, 'check': 51, 'come': 84,
'comparison': 40, 'custom': 61, 'dictionary': 58,
'different': 76, 'difficult': 85, 'do': 86, 'does': 13,
'entire': 37, 'every': 33, 'filled': 77, 'foobarbazz': 20,
'for': 42, 'fuzzy': 53, 'have': 30, 'how': 36, 'however': 68,
'i': 74, 'if': 43, 'implement': 62, 'in': 57, 'information': 46,
'is': 71, 'it': 83, 'like': 64, 'list': 55, 'looping': 70,
'makes': 63, 'match': 16, 'matches': 1, 'member': 29,
'members': 78, 'method': 7, 'might': 6, 'most': 28, 'my': 38,
'name': 18, 'naming': 41, 'of': 52, 'on': 17, 'oop': 35,
'operator': 21, 'over': 19, 'overload': 27, 'own': 72,
'reasons': 79, 'redefine': 10, 'research': 22, 'same': 48,
'search': 75, 'see': 5, 'situation': 39, 'so': 87, 'sounds': 24,
'straightforward': 69, 'stuff': 15, 'such': 66, 'that': 47,
'the': 56, 'then': 54, 'things': 81, 'think': 67, 'this': 59,
'to': 9, 'very': 0, 'want': 23, 'way': 60, 'what': 44,
'whole': 26, 'with': 8, 'without': 65, 'works': 4, 'would': 25,
'yet': 80}
# Example A
for member in my_list:
if dict_contains(my_hash, member):
print('Found:', member)
# Example B
for member in my_list:
match = dict_search(my_hash, member)
if match:
print('Query with', member, 'resulted in', match)
else:
print('Searching with', member, 'failed miserably')
def dict_contains(self, needle):
"""Check if search term can be found in any key of the given dict."""
return any(needle in haystack for haystack in self)
def dict_search(self, pattern):
"""Return the dict's subset where the search term is found in the key."""
return {key: value for key, value in self.items() if pattern in key}
if __name__ == '__main__':
main()