Skip to content

Instantly share code, notes, and snippets.

@AndresMWeber
Last active February 5, 2017 20:38
Show Gist options
  • Save AndresMWeber/76cb74a18ed7d4c682d9cafdbe3b86a4 to your computer and use it in GitHub Desktop.
Save AndresMWeber/76cb74a18ed7d4c682d9cafdbe3b86a4 to your computer and use it in GitHub Desktop.
def gen_dict_key_matches(key, dictionary, path=None, full_path=False):
if path is None:
path = []
for k, v in iteritems(dictionary):
path.append(k)
if k == key:
yield (path, v) if full_path else v
elif isinstance(v, dict):
for result in gen_dict_key_matches(key, v, path):
yield result
from tools import gen_dict_key_matches as ge
print list(ge('nf', {'nf':{'blah':4}})) # no worky
print list(ge('nf', {'nf':5})) # worky
class TestGetKeysContaining(TestBase):
def test_simple(self):
self.assertEquals(get_keys_containing('test', {'test': 1}), 1)
def test_not_existing(self):
self.assertEquals(get_keys_containing('mest', {'test': 1}), None)
def test_mock_config_find(self):
self.checkEqual(list(get_keys_containing('naming_formats', OrderedDict([('overall_config', {'version_padding': 3}),
('options', {
'discipline': {'animation': 'AN ANI ANIM ANIMN', 'lighting': 'LT LGT LGHT LIGHT',
'compositing': 'CM CMP COMP COMPG', 'rigging': 'RG RIG RIGG RIGNG',
'modeling': 'MD MOD MODL MODEL', 'matchmove': 'MM MMV MMOV MMOVE'},
'side': ['left', 'right', 'center']}),
('naming_formats', {
'node': {'default': 'side_location_nameDecoratorVar_childtype_purpose_type',
'format_archive': 'side_name_space_purpose_decorator_childtype_type',
'format_lee': 'type_childtype_space_purpose_name_side'},
'texturing': {'shader': 'side_name_type'}})]))),
['node', 'texturing'])
@ssttuu
Copy link

ssttuu commented Feb 5, 2017

def gen_dict_key_matches(qstring, iterable, path=None, full_path=False):
    """ From:
    http://stackoverflow.com/questions/34836777/print-complete-key-path-for-all-the-values-of-a-python-nested-dictionary
    """
    if path is None:
        path = []

    for k, v in iteritems(iterable):
        new_path = path + [k]
        if k == qstring:
            yield (new_path, v) if full_path else v

        if isinstance(v, dict):
            yield gen_dict_key_matches(qstring, v, new_path)
            

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment