appending to dict

B

bucket79

Hi
is there anyway appending to dictionary?
list has this feature
[1]

but dictionary can't
i wanna do like this thing{1:2, 3:4}

so i try this feature likebut this make's error
because a.keys().append(3) makes 'None' (i can't understand this :( )

so i try copy.copy(a.values()).append(4)))
and
a = dict(zip(copy.deepcopy(a.keys()).append(3),
copy.deepcopy(a.values()).append(4)))
but this make's error, too

why a.keys().append(3) makes 'None' ?
and is there anyway appending to dictionary?

any post will be appreciated :)
 
?

=?ISO-8859-1?Q?Holger_T=FCrk?=

bucket79 said:
why a.keys().append(3) makes 'None' ?

Because .append modifies the list in place. It does
not return a new list.
and is there anyway appending to dictionary?

key/value pairs in a dictionary are not ordered. There
is no "last pair". So you can't append to a dictionary.
But you can update it with another dictionary.
Use something like: adict.update (anotherdict)

keys () returns a list of keys in the dictionary.
The order of the elements in this list is arbitrary
(or somehow ordered afterwards). But there is no
real list of keys in the dictionary itself.

Greetings,

Holger
 
P

Peter Hansen

bucket79 said:
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
{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
 
H

Heather Coppersmith

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,635
Latest member
SkyePurves

Latest Threads

Top