tags:

views:

112

answers:

4

Hi

Is there an easy way to create dictionary like associative array in php? in php i can do:

> $x='a';
> while($x<d){
>     $arr[]['Letter']=$x;
>      $x++
>     }

The interpreter adds automatically a new number into empty brackets "[]" so i can access letter b from $arr[1]['Letter'], etc.

Is there a way to do same with python?

+3  A: 

Edit: I'm stupid. Of course there is a way of doing this in Python. Like so:

result = [{'Letter': chr(i+97)} for i in range(26)]

That will give you a List. Which can be indexed with a number. So result[1]['Letter'] will give you 'b'.

Lennart Regebro
Great solution :) thank you
Chris
+3  A: 

Empty-brackets indexing is syntactically invalid in Python, but you could conceivably program a class that takes e.g. [None] as a signal to add one more key with a dict as its value and an incremented integer as the key. Before I make the substantial effort to program such a class, I'd love to understand what real problem you're trying to solve that, e.g. a collections.defaultdict wouldn't address.

Alex Martelli
As a temporary solution i used defaultdict.
Chris
A: 

Already mentioned that Python doesn't support it by default.

You can achieve that effect by using the length of the dictionary, like this:

>>> arr = {'letter':{1:'a'}}
>>> arr
{'letter': {1: 'a'}}
>>> arr['letter'][len(arr['letter'])+1] = 'b'
>>> arr['letter'][len(arr['letter'])+1] = 'c'
>>> arr['letter'][len(arr['letter'])+1] = 'd'
>>> arr
{'letter': {1: 'a', 2: 'b', 3: 'c', 4: 'd'}}
>>>
Nick D
+1  A: 

In python lists and dictionaries are distinct types. PHP has the one type to rule them all the associative array.

I think what you want to do above translates into a list of dictionaries in python, like this

x = [ dict(Letter=chr(i)) for i in range(ord('a'),ord('f')) ]

If you try this in the interpreter

>>> x = [ dict(Letter=chr(i)) for i in range(ord('a'),ord('f')) ]
>>> x
[{'Letter': 'a'}, {'Letter': 'b'}, {'Letter': 'c'}, {'Letter': 'd'}, {'Letter': 'e'}]
>>> x[0]
{'Letter': 'a'}
>>> x[1]
{'Letter': 'b'}
>>> x[1]['Letter']
'b'
>>>

Or if you prefer it written out in full without a list comprehension

x = []
for c in range(ord('a'),ord('f')):
    d = { 'Letter': chr(c) }
    x.append(d)
Nick Craig-Wood
I think you're the first one here who got what the OP was trying to achieve.
itsadok