Python Dict Methods
dict Methods

Common dictionary methods

Run small interactive examples to see what each method returns.

Picture this: count with a dict

For each word, add 1 to that word’s locker. Missing key starts at 0.

wordnext token
→
d.get(word, 0)old count
→
+ 1new count
→
d[word] = …store

Diagram — count with a dict

word counts[word]++ frequency map

Methods covered

get, setdefault, pop, popitem, update, clear, copy, items/keys/values.

get()

data = {'a':1, 'b':2}
print(data.get('b'))
print(data.get('c', 0))

Result

—

setdefault()

d = {'x':10}
val = d.setdefault('y', 99)
val2 = d.setdefault('x', 0)
print(d)

Result

—

pop() / popitem()

d = {'a':1, 'b':2, 'c':3}
v = d.pop('b')
pi = d.popitem()
print(v, pi, d)

Result

—

update() / copy()

d = {'a':1}
e = {'b':2}
d.update(e)
copy = d.copy()
print(d, copy)

Result

—

items(), keys(), values()

d = {'a':1, 'b':2}
print(list(d.items()))
print(list(d.keys()))
print(list(d.values()))

Result

—