This is weird, first time I'd seen this behaviour when creating a dictionary from enumerated list. Let's say you have a list like this:
>>> a = [1, 8, 6, 2, 5, 4, 8, 3, 7]
>>> for x, y in enumerate(a):
print(x, y)
Out:
0 1
1 8
2 6
3 2
4 5
5 4
6 8
7 3
8 7
This makes sense. And so does this:
>>> foo = {x: y for x, y in enumerate(a)}
>>> foo
Out: {0: 1, 1: 8, 2: 6, 3: 2, 4: 5, 5: 4, 6: 8, 7: 3, 8: 7}
But if I switch index and value around then I get all sorts of weirdness happening:
>>> foo = {y: x for x, y in enumerate(a)}
>>> foo
Out:
{1: 0, 8: 6, 6: 2, 2: 3, 5: 4, 4: 5, 3: 7, 7: 8}
Why did index 1
disappear? Why does value 8
has index 6
instead of 1
?
I don't understand why this is happening and how to correctly write a dictionary comprehension in this case?