0

I have dictionaries I have to iterate like this:

for akey,bdict in cdict.items():
    for dkey,edict in bdict.items():
        for fkey,gdict in edict.items():
            for hkey,ival in gdict.items():
                # do something

How can I define explode so that I can do something like this with an arbitrarily large nested dict (I might need parentheses around some of the iterated items, but use of parentheses will be determined by explode, I would imagine)?

for akey,dkey,fkey,hkey,ival in explode(cdict):
    # do something

# or 

for *keys,val in explode(any_nesteddict):
    # do something

updated after answer from popcorndude on Jul 9 at 23:38

Is there a way to unpack to a certain level in the dictionary eg if I wanted to get akey, dkey, and edict?

for (akey,dkey),edict in explode(cdict, level=2):
    # do stuff

# which is different from original question:
for (akey,dkey,fkey,hkey),ival in explode(cdict):
    # do stuff

BML
  • 191
  • 2
  • 12
  • What have you tried so far? – Klaus D. Jul 09 '21 at 21:08
  • Does this answer your question? [Flatten nested dictionaries, compressing keys](https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys) – Renat Jul 09 '21 at 21:23

1 Answers1

1
def explode(dct):
    # iterate over the top-level dictionary
    k, v in dct.items():
        if isinstance(v, dict):
            # it's a nested dictionary, so recurse
            for ks, v2 in explode(v):
                # ks is a tuple of keys, and we want to
                # prepend k, so we convert it into a tuple
                yield (k,)+ks, v2
        else:
            # make sure that in the base case
            # we're still yielding the keys as a tuple
            yield (k,), v

We need to write (k,) rather than just (k), because tuples in Python are defined by commas, and the parentheses are just for grouping, so (k) == k, but (k,) is a tuple containing k.

popcorndude
  • 123
  • 7