iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Dictionary Methods

Dictionary methods reference. Insertion-ordered since 3.7.

Read

MethodWhat it does
d[k]Value at k; KeyError if missing.
d.get(k, default=None)Value or default — never raises.
k in dMembership test.
len(d)Number of keys.

Write

MethodWhat it does
d[k] = vSet / replace.
d.setdefault(k, v)Insert v if missing, return current value.
d.update(other)Merge another dict (or iterable of pairs).
d \| other / d \|= otherMerge operators (3.9+).

Remove

MethodWhat it does
d.pop(k, default=…)Remove and return value.
d.popitem()Remove and return the last inserted (k, v).
del d[k]Statement form.
d.clear()Empty the dict.

Iterate

MethodWhat it does
d.keys() / d.values() / d.items()Live views.
PYTHON
for k, v in d.items():
    print(k, v)

Build with comprehensions

PYTHON
squares = {n: n * n for n in range(5)}
inverted = {v: k for k, v in d.items()}

Specialised dicts

ClassWhy
collections.defaultdictAuto-creates missing keys with a factory.
collections.CounterCounting hashables.
collections.OrderedDictPredates 3.7; adds move_to_end().
collections.ChainMapStack of dicts; lookups fall through.
Tip: Use d.get(k, default) for read fallbacks and defaultdict(list) for accumulator patterns. Each saves an "if key in dict" check.

Example

Example
d = {'a': 1, 'b': 2}
print(d.keys(), d.values(), d.items())
print(d.get('c', 0))
d.update({'c': 3})
print(d)
Try it Yourself »

Exercise

Iterate (key, value) pairs.

for k, v in d. ():

Test yourself

Q1. Items view yields…
Q2. For accumulators prefer…
Q3. Counter is from…

Discussion

Loading…