Python Functions and Methods: A Topic-by-Topic Reference · Lesson 8 of 12

Lesson 8: Dictionary Methods

get, keys, values, items, update, pop, setdefault, merging, dictionary comprehensions, fromkeys and sorting a dictionary.

Lesson 8: Dictionary Methods

A dictionary maps keys to values. Looking up a key is very fast, however large the dictionary is. Keys must be unchangeable (text, numbers, tuples).

Reading

d[key] and d.get(key, default)

d[key] raises an error when the key is missing; get returns a default instead.

ages = {"Ram": 17, "Sita": 19}
print(ages["Ram"])
print(ages.get("Hari"))
print(ages.get("Hari", 0))

Output:

17
None
0

keys(), values(), items()

Views of the keys, the values, or the (key, value) pairs.

d = {"a": 1, "b": 2}
print(list(d.keys()))
print(list(d.values()))
print(list(d.items()))
for k, v in d.items():
    print(k, "->", v)

Output:

['a', 'b']
[1, 2]
[('a', 1), ('b', 2)]
a -> 1
b -> 2

in

Checks the keys.

d = {"a": 1}
print("a" in d, "b" in d, 1 in d)

Output:

True False False

Changing

d[key] = value

Adds a new key or replaces an existing value.

d = {"a": 1}
d["b"] = 2
d["a"] = 100
print(d)

Output:

{'a': 100, 'b': 2}

update(other)

Adds or overwrites keys from another dictionary. | (Python 3.9+) does the same into a new one.

a = {"x": 1, "y": 2}
b = {"y": 20, "z": 30}
a.update(b)
print(a)
print({"p": 1} | {"q": 2})

Output:

{'x': 1, 'y': 20, 'z': 30}
{'p': 1, 'q': 2}

setdefault(key, default)

Returns the value if the key exists; otherwise stores and returns the default. Great for grouping.

groups = {}
for word in ["apple", "avocado", "banana", "blueberry", "cherry"]:
    groups.setdefault(word[0], []).append(word)
print(groups)

Output:

{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

pop(key, default), popitem(), del, clear()

Remove a key (returning its value), the last added pair, or everything.

d = {"a": 1, "b": 2, "c": 3}
print(d.pop("a"))
print(d.pop("zz", "missing"))
del d["b"]
print(d)
print(d.popitem())
print(d)

Output:

1
missing
{'c': 3}
('c', 3)
{}

Building

dict comprehension

Build a dictionary from any iterable.

print({n: n ** 2 for n in range(1, 5)})
print({w: len(w) for w in ["red", "green", "blue"]})

Output:

{1: 1, 2: 4, 3: 9, 4: 16}
{'red': 3, 'green': 5, 'blue': 4}

dict(zip(keys, values))

Combine two lists into a dictionary.

names = ["Ram", "Sita"]
marks = [80, 92]
print(dict(zip(names, marks)))

Output:

{'Ram': 80, 'Sita': 92}

dict.fromkeys(keys, value)

A dictionary with the same starting value for every key.

print(dict.fromkeys(["a", "b", "c"], 0))

Output:

{'a': 0, 'b': 0, 'c': 0}

Inverting a dictionary

Swap keys and values (values must be unique and unchangeable).

d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()})

Output:

{1: 'a', 2: 'b'}

Sorting and finding

Sorting by key or by value

sorted(d) sorts the keys; sort d.items() with a key to sort by value.

scores = {"Ram": 70, "Sita": 95, "Hari": 82}
print(sorted(scores))
print(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
print(max(scores, key=scores.get))

Output:

['Hari', 'Ram', 'Sita']
[('Sita', 95), ('Hari', 82), ('Ram', 70)]
Sita

Nested dictionaries

Dictionaries can hold dictionaries and lists. Chain the lookups.

school = {"class10": {"Ram": 80, "Sita": 90}, "class11": {"Hari": 70}}
print(school["class10"]["Sita"])
for cls, kids in school.items():
    print(cls, sum(kids.values()) / len(kids))

Output:

90
class10 85.0
class11 70.0

Counting with a dictionary

The classic pattern. (Lesson 11 shows the shortcut, Counter.)

counts = {}
for ch in "mississippi":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

Output:

{'m': 1, 'i': 4, 's': 4, 'p': 2}

Since Python 3.7 a dictionary remembers the order in which keys were added.

Try it yourself

  1. Count how many times each word appears in a sentence.
  2. Group a list of marks into "pass" and "fail" with setdefault.
  3. Find the key with the highest value.

Next lesson: map, filter, zip and friends.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 8: Dictionary Methods | MeroSir