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
dict.get
Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None so this method never raises a KeyError.
dict.update
Updates the dictionary in place with key/value pairs from other, overwriting existing keys. Accepts another mapping, an iterable of key/value pairs, and/or keyword arguments; returns None.
key in dict
Membership test invoking __contains__ — returns True if key exists in the dictionary. The check is against keys only (never values) and runs in O(1) average time.
dict.pop
Removes the specified key and returns its value. If the key is missing, returns default if provided; otherwise raises KeyError.
dict.popitem
Removes and returns the last inserted (key, value) pair as a 2-tuple in LIFO order. Raises KeyError if the dictionary is empty.
← All Python dict methods · String methods · Built-in functions