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
Member Avatar for Enalicho

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.

commented: 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. -1
Member Avatar for Enalicho

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.

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

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.