Skip to content

Instantly share code, notes, and snippets.

@theY4Kman
Last active May 8, 2016 16:39
Show Gist options
  • Select an option

  • Save theY4Kman/c91155aeddbe01ba0dff to your computer and use it in GitHub Desktop.

Select an option

Save theY4Kman/c91155aeddbe01ba0dff to your computer and use it in GitHub Desktop.
Ever had an enormous dict you needed to search for a simple string?
import re
def search(d, pattern, name='root'):
if not hasattr(pattern, 'match'):
pattern = re.compile(re.escape(pattern), re.I)
results = []
_keystr = lambda key, item: '%s[%r]' % (key, item)
def _value(v, key):
# TODO: how to key set?
if isinstance(v, (list, tuple, set)):
for i, c in enumerate(v):
_value(c, _keystr(key, i))
elif isinstance(v, dict):
for k, v in v.iteritems():
_value(v, _keystr(key, k))
else:
v = str(v)
_check(v, key)
def _check(s, key):
match = pattern.search(s)
if match:
results.append((key, s))
_value(d, name)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment