-1

I was trying to get a nested dictionary comprehension to work after I found out how a nested list comprehension worked. I succesfully created the nested dictionary comprehension, although I'm still confused why the syntax is different. In the nested list comprehension the inner loop is within the outer loop so to say, while for the dictionary the inner loop follows the outer loop.

Example:

alist = [[1,2,3],[4,5,6],[7,8,9]]

print([[[xi, index] for index, xi in enumerate(x) ] for x in alist])

print({xi: index for x in alist for index, xi in enumerate(x)})

[[[1, 0], [2, 1], [3, 2]], [[4, 0], [5, 1], [6, 2]], [[7, 0], [8, 1], [9, 2]]]
{1: 0, 2: 1, 3: 2, 4: 0, 5: 1, 6: 2, 7: 0, 8: 1, 9: 2}

Can someone clarify this difference in syntax, or am I doing something wrong here?

Michael
  • 1,281
  • 1
  • 17
  • 32

1 Answers1

0

Perhaps it would be easier to see if you expanded both loops, in the first case you see your result has sublists that get appended to a larger list, that is the creates that inner layer of blocking in your list comprehension and must be accompanied with its for index, xi in enumerate(x). When we look at the bottom dicitonary comprehension you are creating a flat dictionary that gets appended to one list so there is no inner block in your dictionary comprehension

lst = []
for x in alist:
    new = []
    for index, xi in enumerate(x):
        new.append([xi, index])
    lst.append(new)

print(lst)
# [[[1, 0], [2, 1], [3, 2]], [[4, 0], [5, 1], [6, 2]], [[7, 0], [8, 1], [9, 2]]]


d = {}
for x in alist:
    for index, xi in enumerate(x):
        d[xi] = index
print(d)
# {1: 0, 2: 1, 3: 2, 4: 0, 5: 1, 6: 2, 7: 0, 8: 1, 9: 2}

Another example would be creating a nested dictionary comprehension would help as well

print({alist.index(x):{xi:index for index, xi in enumerate(x)} for x in alist})
# {0: {1: 0, 2: 1, 3: 2}, 1: {4: 0, 5: 1, 6: 2}, 2: {7: 0, 8: 1, 9: 2}}
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20