Skip to content


Quick Tip – Python 2D+ Dictionaries

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)])
print d_arr[0,1] # 0
d_arr[0,1]=5
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

d_arr = {}
d_arr[1,3] = 5
print d_arr[1,3] # 5

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)])
print d_arr["s1-0","s2-1"] # 0
d_arr["s1-0","s2-1"] = 5
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.

Posted in Tutorials.


One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Chris Robinson says

    I love python



Some HTML is OK

or, reply to this post via trackback.

 



Log in here!