(newbie) Array of dictionaries

Quinn Dunkan quinn at lira.ugcs.caltech.edu
Sat Oct 2 22:48:38 EDT 1999


On Sat, 02 Oct 1999 12:29:39 -0700, Marty Brundage <brundage at aimnet.com> wrote:
>
>Yes, and it works for me.  I didn't think it would be this simple!  (I
>was looking for an explicit declaration, and got hung up on that
>issue.)
>
>Some replies have pointed out an explicit declaration syntax of
>
>a=[{},{},...]
>
>Which is only good for small fixed length arrays of dictionaries.  It
>seems odd that the general case does not require an explicit
>delaration.

In pythonworld, an explicit declaration existing at all would be odd (except
for "global").  "a = [{}, {}, ...]" is not a declaration at all, it creates an
array and some dicts (which happen to be empty) and binds them to "a", just
like if you said "a = 5".

If you want to append dicts to your list sequentially, then the append()
method is for you.  If, however, you want to insert a dict at any point
without having to generate all the elements in between, you might want to use
another dict:

a = {}
a[5] = {'foo': 'bar'} # dicts can be keyed by any immutable type

A lot of people coming from more static languages have this problem:
"I didn't think it would be this simple!"

And if that's the biggest problem you have, you'll be a fan in no time :)




More information about the Python-list mailing list