FancyDolphin
FancyDolphin

Reputation: 457

Iterating over a nested dictionary

Purpose this code that works to iterate over a nested dictionary but I'm looking for an output that gives a tuple or list of [keys] and then [values]. Here's the code:

from collections import Mapping, Set, Sequence

string_types = (str, unicode) if str is bytes else (str, bytes)
iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()

def recurse(obj, path=(), memo=None):
    if memo is None:
        memo = set()
    iterator = None
    if isinstance(obj, Mapping):
        iterator = iteritems
    elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
        iterator = enumerate
    if iterator:
        if id(obj) not in memo:
            memo.add(id(obj))
            for path_component, value in iterator(obj):
                for result in recurse(value, path + (path_component,), memo):
                    yield result
            memo.remove(id(obj))
    else:
        yield path, obj


class addNestedDict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

loansDict=addNestedDict()
loansDict[15]['A']['B']=[1,2,3,4]

for k,v in recurse(loansDict):
    print(k,v)

The output I'm looking for is one line (15 ,'A','B') [1,2,3,4] so that I can be able to reference k[0],k[1] and v[0] etc...

Upvotes: 0

Views: 91

Answers (1)

martineau
martineau

Reputation: 123473

This seems to work:

results = AddNestedDict()
for k,v in recurse(loansDict):
    results.setdefault(k[:-1], []).append(v)
result_key, result_value = results.items()[0]
print('{} {}'.format(result_key, result_value))  # -> (15, 'A', 'B') [1, 2, 3, 4]

I renamed your class AddNestedDict so it follows PEP 8 guidelines.

Upvotes: 1

Related Questions