1

I' trying to create a PHP like array in python. In Perl it would be a hash...

I want to organize content from the database in an array for easier access.

Something like:

myarray[db_numeric_value1][db_numeric_value2] = db_str_value

But no luck so far...

I tried to initialize myarray as an object list (myarray = {}) or as an array (myarray = [])... Also tried to initialize the "subarrays" but did not work either...

Thanks for your help!

Ron

1

2 Answers 2

2

you may use python's defaultdict with proper "default_factory":

from collections import defaultdict
myarray = defaultdict(dict)
myarray[4][5] = 34
Sign up to request clarification or add additional context in comments.

Comments

1

In Python it would be a dictionary (see python data structures)

In [4]: myarray = {3: {4: 'Hello World'}}

In [5]: myarray[3][4]
Out[5]: 'Hello World'

EDIT: the same thing but without initializing first

In [6]: myarray = {}
In [7]: myarray[3] = {}
In [9]: myarray[3][4] = 'Hello World'

In [10]: myarray[3][4]
Out[10]: 'Hello World'

Dictionary indexes can be also variables:

myarray[myindex] = myvalue

6 Comments

AFAIK I tried to use a list when I initialized myarray with these brackets: []... When do this, Python tells me that my list index is out of range... The thing is that its a dynamical list so there should be no boundry, right?
Thanks for the code snippet...but how do I do this dynamically. The thing is that I dont know my values because I get them from my database...
Ok... I really think I'm missing something... When I try your static code it works just fine. As soon as I put a variable between the brackets he complains... the error is just the key. for example: myarray[val] = "foo" then the error is just val, ie. 3
Show the exact code that fails, including all setup steps and the traceback.
myarray always has to be a dictionary first: myarray = {}
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.