Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten a Dictionary using Yield

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    {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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading