This code example shows how to create a dictionary with row,column indexed (r,c) key tuples
from a typical list of lists 2D matrix. Also an example is shown of the ease of processing the resulting dictionary.
A Matrix Dictionary (Python)
''' 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
'''
GaryBaird 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
paddy3118 11 Light Poster
TrustyTony 888 pyMod Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.