appending to dict

Peter Hansen peter at engcorp.com
Fri May 14 07:16:01 EDT 2004


bucket79 wrote:

> is there anyway appending to dictionary?
> list has this feature
> 
>>>>a = []
>>>>a.append(1)
>>>>print a
> [1]
> 
> but dictionary can't
> i wanna do like this thing
> 
>>>>a = {1, 2}
>>>>a.append(3, 4) -> This is just my idea :@
>>>>print a
> {1:2, 3:4}

Did you know that the following actually works?

 >>> a = {1: 2}   # note: your syntax was wrong here
 >>> print a
{1: 2}
 >>> a[3] = 4
 >>> print a
{1: 2, 3: 4}

Since, as Holger pointed out, dictionaries aren't ordered,
the concept implicit in "append" doesn't apply.  The more
appropriate concept "update", however, can be spelled either
dict.update(), or like what I just showed, for dictionaries.

-Peter



More information about the Python-list mailing list