Cody A. Ray

Quick Tip - Python 2D+ Dictionaries

December 1, 2010

_So you want 2D or larger multidimensional arrays in Python, huh?
_

Like me, you’re probably too lazy (or realize its overkill) to extend the built-in array class to do this, as some solutions suggest. Of course, the most natural solution (though a hack using tuples) uses features of Python3 that those of us rocking Python2 can’t use. But don’t give up hope-there is a way!

d_arr = dict([[(x,y),0] for x in range(3) for y in range(4)])<br />
print d_arr[0,1] # 0<br />
d_arr[0,1]=5<br />
print d_arr[0,1] # 5

As you can see, this initializes each N-dimensional “cell” to zero. And if you don’t need an initializer, as above, you can just use the dictionary directly as

<br />
d_arr = {}<br />
d_arr[1,3] = 5<br />
print d_arr[1,3] # 5<br />

If you like it, go use it in a project!

But if, for some reason, you don’t believe this is really a dictionary because of the integer keys, try this:

d_arr = dict([[("s1-%d"%x,"s2-%d"%y),0] for x in range(3) for y in range(4)])<br />
print d_arr["s1-0","s2-1"] # 0<br />
d_arr["s1-0","s2-1"] = 5<br />
print d_arr["s1-0","s2-1"] # 5

And, yes, I avoided using spaces in the example above just because you doubted me. Believers would’ve already been moving on to the next part of their project using the beautifully simple solution above.

1 comment

Imported from the previous site.

Chris Robinson· December 1, 2010
I love python
© 2009–2026 Cody A. Ray
RSSGitHubLinkedIn