How to add a key:datum pair to the dictionary

Tim Peters tim_one at email.msn.com
Sun May 16 14:59:07 EDT 1999


[MK]
> I have stumbled across a stupid problem: how to add a pair to
> dictionary like
>
> {'mk': {'repetitions': 20, 'no match': 10}}
>
> I have not found the method for this anywhere in documentation.
> Dictionary is mutable, but neither Library Reference nor Language
> Reference give information on how to _add_ something to dictionary.
> It seems strange -- I mean, is creating dictionary and then changing
> items in it the only possible method of changing dictionary? Can it be
> enlarged?

Oh sure.  Just assign:

>>> d = {}
>>> d['hi'] = 'ho'
>>> d
{'hi': 'ho'}
>>> d['another'] = (1,2,3)
>>> d
{'hi': 'ho', 'another': (1, 2, 3)}
>>> d[(1,2,3)] = (3,2,1)
>>> d
{'hi': 'ho', 'another': (1, 2, 3), (1, 2, 3): (3, 2, 1)}
>>> d.keys()
['hi', 'another', (1, 2, 3)]
>>> d.values()
['ho', (1, 2, 3), (3, 2, 1)]
>>> d.items()
[('hi', 'ho'), ('another', (1, 2, 3)), ((1, 2, 3), (3, 2, 1))]
>>>

Your copy of Python should have come with a Tutorial, which you should find
and work your way through.  A brief intro to dicts is in section 5.4.

not-only-possible-but-easy!-ly y'rs  - tim






More information about the Python-list mailing list