mutation

dict[key] = value

Assigns value to key using bracket subscription syntax, invoking __setitem__ under the hood. Creates the entry if key is absent, or overwrites the existing value; preserves the original insertion order when the key already exists.

d[key] = value

Parameters

Parameter Purpose
key Any hashable value (str, int, tuple of hashables, ...)
value Any Python object — no restriction

Examples

>>> d = {}
>>> d['a'] = 1
>>> d
{'a': 1}

Assignment creates the key

>>> d = {'a': 1, 'b': 2}
>>> d['a'] = 99
>>> d
{'a': 99, 'b': 2}

Overwrites without changing insertion position

>>> d = {}
>>> d[[1,2]] = 'x'
Traceback (most recent call last):
  ...
TypeError: unhashable type: 'list'

Keys must be hashable — lists and dicts are not

>>> d = {}
>>> d[(1, 2)] = 'point'
>>> d
{(1, 2): 'point'}

Tuples of hashables are valid keys

Gotcha

Keys must be hashable (immutable) — using a list, dict, or set as a key raises TypeError. Overwriting an existing key preserves its original insertion order; new keys go to the end.

Related methods

← All Python dict methods · String methods · Built-in functions