Home > Blockchain >  Flatten a Dictionary using Yield
Flatten a Dictionary using Yield

Time:11-22

My code is as follows:

def und1(d):
    for i in d:
        if type(d[i])==dict:
             und1(d[i])
        else:
            yield({i:d[i]})
Dict1 = {1: 'Geeks', 2: 'For', 3: 'Geeks',4:{5:'wevcn '}}
for z in  und1(Dict1):
    print(z)

I am currently getting output:

{1: 'Geeks'}
{2: 'For'}
{3: 'Geeks'}

Expected output:

    {1: 'Geeks'}
     {2: 'For'}
    {3: 'Geeks'}
    {5:'wevcn'}

Issue: My function is not calling recurisve function it is returning null. Can some tell me why?

CodePudding user response:

Your code should use yield from and can be simplified like this:

def und1(d):
    for k, v in d.items():
        if isinstance(v, dict):
            yield from und1(v)
        else:
            yield {k: v}


dict1 = {1: 'Geeks', 2: 'For', 3: 'Geeks', 4: {5: 'wevcn '}}
for z in und1(dict1):
    print(z)

The isinstance() is specifically useful to check if "something is a ..." and by iterating over .items() of a dict, you can easily get access to both the key and value, so you don't have to index the dict again.

The output:

{1: 'Geeks'}
{2: 'For'}
{3: 'Geeks'}
{5: 'wevcn '}

In your code, a generator was returned from the function (as it does yield for non-dict items) and since you called the function, but didn't assign the function result to anything, that generator got discarded.

You could assign the function result to a variable and iterate over that, but there's no need for what you want with it.

  • Related