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

two for loop not working properly in dict comprehension

recipe = {
    "butter chicken" : "Value",
    "pepper chicken" : "Value",
    "garlic chicken" : "Value",
    "ginger chicken" : "Value",
    }

dict comprehension is

{key : value for key in range(1, len(recipe)+1) for value in recipe}   

this is printing

{1: 'ginger chicken', 2: 'ginger chicken', 3: 'ginger chicken', 4: 'ginger chicken'}

actually i want

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: 'butter chicken', 2: 'pepper chicken', 3: 'garlic chicken', 4: 'ginger chicken'}

>Solution :

You can use enumerate for this:

listrecipe = dict(enumerate(recipe, 1))

Output:

{1: 'butter chicken', 2: 'pepper chicken', 3: 'garlic chicken', 4: 'ginger chicken'}

If you prefer dict-comprehension with range, then it should be:

{key: value for key, value in zip(range(1, len(recipe)+1), recipe)}

Why your solution isn’t working?

listrecipe = {key : value for key in range(1, len(recipe)+1) for value in recipe}   

is equivalent to:

listrecipe = {}

for key in range(1, len(recipe)+1):
    for value in recipe:
        listrecipe[key] = value

So for each key (from 1 to len(recipe)+1) you write each value, so each next value overrides the previous one. That’s why only last value is left for every key.

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