Search code examples
pythondictionaryfor-looplist-comprehension

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

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