Home > Net >  Python Dictionary Comprehension Not Outputting As Expected
Python Dictionary Comprehension Not Outputting As Expected

Time:10-05

I am playing around with dictionaries, and thought how would I create a dictionary using comprehensions. I thought

{k:v for k in [0,1,2] for v in [5,8,7]}

would print as

{0:5, 1:8, 2:7}

But instead it prints as

{0: 7, 1: 7, 2: 7}

Why is this happening and what modifications would I need to make to get the first output?

CodePudding user response:

Your list comprehension is equivalent to nested loops:

result = {}
for v in [5, 8, 7]:
    for k in [0, 1, 2]:
        result[k] = v

So each iteration of the outer loop sets all the keys to that value, and at the end you have the last value in all of them.

Use zip() to iterate over two lists in parallel.

{k: v for k, v in zip([0, 1, 2], [5, 8, 7])}

You can also just use the dict() constructor:

dict(zip([0, 1, 2], [5, 8, 7]))

CodePudding user response:

Whenever you have trouble with a comprehension, unroll it into the equivalent loops. Which in this case goes:

mydict = {}
for v in [5,8,7]:
    for k in [0,1,2]:
        mydict[k] = v

Each successive assignment to mydict[k] overwrites the previous one.

  • Related