The example shows how to establish a dictionary of (row, column):value pairs to mimic a two dimensional array. This can be easily expanded to more dimensions. Python3 has dictionary comprehension, making the process of creating a dictionary of this type easier.
Multidimensional Array using a Dictionary (Python)
# use Python3's dictionary comprehension to mimic
# a 2 dimensional array with a dictionary
# with (row, column) index tuples as keys
# tested with Python 3.1.2 by vegaseat
def print_sortkey(d):
"""
print dictionary d with keys sorted
"""
for key in sorted(d):
print( "%s --> %s" % (key, d[key]) )
# create a 3 x 4 2D-array using a dictionary with index tuples
# as keys, initialize with zero
d_arr = {(x,y):0 for x in range(3) for y in range(4)}
print( d_arr )
print( '-'*20 )
"""my result (tuples are in hash order) -->
{(0, 1): 0, (1, 2): 0, (0, 0): 0, (2, 1): 0, (0, 2): 0, ...}
"""
# change some values, basically assign to index
d_arr[2, 1] = 5
# or ...
row = 1
col = 0
d_arr[row, col] = 7
# or ...
ix = (0, 0)
d_arr[ix] = 9
print_sortkey( d_arr )
print( '-'*20 )
"""my result (sorted by index tuple) -->
(0, 0) --> 9
(0, 1) --> 0
(0, 2) --> 0
(0, 3) --> 0
(1, 0) --> 7
(1, 1) --> 0
(1, 2) --> 0
(1, 3) --> 0
(2, 0) --> 0
(2, 1) --> 5
(2, 2) --> 0
(2, 3) --> 0
"""
# get a specific value from a given index tuple
print( d_arr[0, 0] ) # 9
# or ...
row = 0
col = 0
print( d_arr[row, col] ) # 9
# or ...
ix = (0, 0)
print( d_arr[ix] ) # 9
Skrell 0 Light Poster
Ene Uran 638 Posting Virtuoso
Skrell 0 Light Poster
RLS0812 -3 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Skrell 0 Light Poster
Founder_1 0 Newbie Poster
Gunjan_2 0 Newbie Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
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.