All courses › Programming with Python › Dictionary (dict)

Dictionary (dict)

A dictionary, {"a": 1}, stores key–value pairs. You get a value with d[key] or safely with d.get(key, default), which does not error if the key is missing. Assigning a new key adds it.

d[k]d[k]the value for key kk
d.get(k,v0)d.\text{get}(k, v_0)the value for kk, or v0v_0 if kk is missing

Symbols

dda dictionary
kka key
v0v_0default value

Example

d = {"a": 2, "b": 7}

d.get("c", 3) gives 3, since "c" is not in d.

d[k] raises KeyError if the key is missing — use .get when unsure.
Practise functions and data structures for free →

← Functions and return · String methods →

Part of Programming with Python: Functions and data structures.