views:

2675

answers:

4

Hi,

Is it possible to add a key to a python dictionary after it has been created? It doesn't seem to have an .add() method...

A: 
dictionary[key] = value
Jason Creighton
+8  A: 
>>> d = {'key':'value'}
>>> print d
{'key': 'value'}
>>> d['mynewkey'] = 'mynewvalue'
>>> print d
{'mynewkey': 'mynewvalue', 'key': 'value'}
Paolo Bergantino
http://docs.python.org/tutorial/datastructures.html#dictionarieshttp://docs.python.org/library/stdtypes.html#mapping-types-dict
Miles
Heh, now I feel kind of stupid.
lfaraone
+2  A: 

Yeah, it's pretty easy. Just do the following:

dict["key"] = "value"
ReadySquid
A: 
>>> x = {1:2}
>>> print x
{1: 2}

>>> x.update({3:4})
>>> print x
{1: 2, 3: 4}
Anton Bessonov