''' dict_2d_array1.py
create a dictionary with row,column indexed (r,c) key tuples
representing a row by column 2D matrix, index is zero based
tested with Python273 and Python33  by  vegaseat  22jan2013
'''

import pprint

# create a 3 by 4 dictionary from a 3 by 4 matrix
matrix34 = [
[2.5, 3.0, 4.0, 1.5],
[1.5, 4.0, 2.0, 7.5],
[3.5, 1.0, 1.0, 2.5]
]
# use dictionary comprehension
dic_rc34 = {(rx, cx): c for rx, r in enumerate(matrix34)\
                for cx, c in enumerate(r)}

pprint.pprint(matrix34, width=30)
print('-'*32)
# show the dictionary of the matrix
pprint.pprint(dic_rc34)

print('-'*30)

# sum the third column (has col index 2)
cx = 2
sf = "sum of third column = {}"
print(sf.format(sum([dic_rc34[rx, cx] for rx in range(3)])))

# sum the fourth column (has col index 3)
cx = 3
sf = "sum of fourth column = {}"
print(sf.format(sum([dic_rc34[rx, cx] for rx in range(3)])))

'''result ..
[[2.5, 3.0, 4.0, 1.5],
 [1.5, 4.0, 2.0, 7.5],
 [3.5, 1.0, 1.0, 2.5]]
------------------------------
{(0, 0): 2.5,
 (0, 1): 3.0,
 (0, 2): 4.0,
 (0, 3): 1.5,
 (1, 0): 1.5,
 (1, 1): 4.0,
 (1, 2): 2.0,
 (1, 3): 7.5,
 (2, 0): 3.5,
 (2, 1): 1.0,
 (2, 2): 1.0,
 (2, 3): 2.5}
------------------------------
sum of third column = 7.0
sum of fourth column = 11.5
'''

Thought you might want to know what you have posted won't work as it's incomplete.

SyntaxError on the column index:
ln,16 'dic_rc34 = {(rx, cx): c for rx, r in enumerate(matrix34)\'
It will error on the first 'for' loop with a 'SyntaxError: invalid syntax'
You may want to repost after fixing this. :)

Works just fine for me. BTW, line 17 is the continuation of line 16.
If you use an older version of Python (older than 2.7), it may not have dictionary comprehension yet.

As of this date please upgrade your Python2 version to 2.7.4
and Python3 version to 3.3.1

Edited 3 Years Ago by vegaseat

It is good to know both methods of representing a 2D array - list of lists and dictionary mapping index pairs to values.

In this particular case though, you can transpose a list using zip(*matrix) to give these results:

>>> matrix34 = [
[2.5, 3.0, 4.0, 1.5],
[1.5, 4.0, 2.0, 7.5],
[3.5, 1.0, 1.0, 2.5]
]
>>> list(zip(*matrix34))
[(2.5, 1.5, 3.5), (3.0, 4.0, 1.0), (4.0, 2.0, 1.0), (1.5, 7.5, 2.5)]
>>> sum(list(zip(*matrix34))[2])
7.0
>>> sum(list(zip(*matrix34))[3])
11.5
>>> 

BTW, line 17 is the continuation of line 16.

Which is not necessary as the { gives automatic line continuation ;)

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.