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

Ron
  • 22,128
  • 31
  • 108
  • 206

2 Answers2

2

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

from collections import defaultdict
myarray = defaultdict(dict)
myarray[4][5] = 34
claperius
  • 311
  • 7
  • 16
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
Diego Navarro
  • 9,316
  • 3
  • 26
  • 33
  • 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? – Ron Jun 01 '12 at 08:03
  • 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... – Ron Jun 01 '12 at 08:05
  • 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 – Ron Jun 01 '12 at 08:13
  • Show the **exact** code that fails, including all setup steps and the traceback. – Daniel Roseman Jun 01 '12 at 08:17
  • `myarray` always has to be a dictionary first: `myarray = {}` – Diego Navarro Jun 01 '12 at 08:18
  • i did this... but the other solution works just fine. nevertheless: thanks :) – Ron Jun 01 '12 at 08:23