Use a dict comprehension. The key to reading nested comprehensions: "Just read them like normal loops, with the “big loop” described first and the subsequent loops nested inside of it" 1
In [1]: lines = ['abc','456','xyz']
In [2]: {(i,j): c for i, row in enumerate(lines) for j, c in enumerate(row)}
Out[2]:
{(0, 0): 'a',
(0, 1): 'b',
(0, 2): 'c',
(1, 0): '4',
(1, 1): '5',
(1, 2): '6',
(2, 0): 'x',
(2, 1): 'y',
(2, 2): 'z'}
You can split the comprehension to multiple lines, to make it more readable. If you look closely it is actually very similar to a regular loop, only the last line is brought to the start.
In addition to that I would recommend reading a blog post by Brandon Rhodes: "I finally understand nested comprehensions"
# Comprehension # Regular for loop
{(i,j):c # chars = {}
for i, row in enumerate(lines) # for i, row in enumerate(lines):
for j, c in enumerate(row)} # for j, c in enumerate(row):
# chars[i,j] = c
chars = map(list, lines)creates a 2d list that allows to change the strings e.g.,chars[i][j] = 'c'. You could also usebytearrayinstead oflisthere depending on howcharsis used.