Multidimensional arrays - how?

Brian Quinlan brian at sweetapp.com
Fri May 3 17:27:45 EDT 2002


 > Yes , but what if I would like to use string keys instead of numbers?
> E.g.
> 
> book, chapter, para = 'a', 'b', 'c' ?
> 
> x = [[['para0', 'para1']]] # will not work as I wanted

> Nested lists are easer implemented in PHP, I am afraid.
> $x['a']['b']['c'] = 'txt' works without any problem.

That's because PHP doesn't have a "list" type. It has an associative
array type that is similar to Python's dictionary. The nice thing about
PHP having a single indexable type is that it can offer you some
syntactic sugar. The down side is that it is less flexible and can't
offer O(1) access.

PHP: 

$x['a']['b']['c'] = 'txt'

Python:
x = {}
x.setdefault('a', {}).setdefault('b', {})['c'] = 'txt'

But in Python, one would be more likely to use a different data
structure, like maybe a class.

Cheers,
Brian






More information about the Python-list mailing list