954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

3D Dict Arrays

While correcting errors in someone else's code, I decided to completely rewrite the original script, and improve upon it.
This is the basic code for making 3D arrays using dictionaries.

ar = { (x,y,z):0                            # creating the array
       for x in range(3)
       for y in range (3)
       for z in range (3)} 
ar [2,1,0] = 777                            # random value
ar [2,2,1] = 2345                           # random value
for x in sorted(ar):                        #output
    print(str(x) + " --- " + str(ar[x]))    #print output
RLS0812
Newbie Poster
12 posts since Dec 2011
Reputation Points: 7
Solved Threads: 0
 

I hate to say this, but what you've got there is only a slightly more convenient way to produce 3 dimensional lists, without any bounds.


The whole thing about arrays is that -
They're fixed in size.
They're fixed in type.
They're in order (note, don't confuse this with sorted).
They're fast, because of those features.

Your code is neither of these; I could do

ar[3,4,5,6] = "hi"


And it'd let me.

No, if you need true arrays then using numpy is the only sensible option.

Enalicho
Junior Poster in Training
62 posts since Aug 2011
Reputation Points: 28
Solved Threads: 13
 
This is an apples to oranges comparison. Dictionaries are sparse data structures and keys can be any hashable objects. Whether someone should use dictionaries, NumPy, or something else depends on what he or she needs.

You seem to mistunderstand my point - the example is *not* an array, but rather merely a way to create some collection with a default size with tuple indexing. This is not Pythonic, it's a work around for people who don't like Python syntax - it goes horribly against OOTD.

If you want *an array* then numpy *is* the way to go - this is not an efficient data structure.

Enalicho
Junior Poster in Training
62 posts since Aug 2011
Reputation Points: 28
Solved Threads: 13
 

Of course numpy limits you to numeric arrays.
A dictionary is a very efficient object in Python.
The language itself uses it internally.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: