Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 149 ยท Data Structures

Dictionary Methods

Master Python dictionary methods. Use get and setdefault for missing keys, update and the | operator to merge, pop and popitem to remove, and views to inspect data.

In Dictionaries you learned the basics: square brackets to read and write, del to remove, and loops over items(). That's enough to get going, but real programs constantly face the same small problems. What if a key might be missing? How do you combine two dictionaries? How do you group items into lists without a pile of if statements?

Dictionaries come with a compact set of methods that solve these problems cleanly. This lesson walks through every one you'll use regularly, grouped by the job they do, plus the merge operators | and |=.

Here's the whole toolbox at a glance:

Method Job
get(key, default=None) Read a value, with a fallback for missing keys
setdefault(key, default=None) Read a value, inserting the default first if it's missing
update(other) Add or overwrite entries from another mapping or pairs
pop(key[, default]) Remove a key and return its value
popitem() Remove and return the most recently added pair
keys(), values(), items() Live views of the dictionary's contents
copy() A shallow copy
clear() Remove everything
dict.fromkeys(keys, value=None) Build a new dictionary from a list of keys

Reading safely: get()

get() returns the value for a key, or a default when the key is missing. The default is None unless you pass your own:

Python get() with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

get() never modifies the dictionary. It's the right choice for optional settings and lookups where a missing key is perfectly normal.

Note: If a key exists with the value None, get() returns None too, so you can't tell "missing" from "stored as None" that way. When the difference matters, test with key in d.

Read or insert: setdefault()

setdefault(key, default) is like get() with one twist: if the key is missing, it first stores the default under that key, then returns it. That makes it perfect for grouping, where each key holds a list you keep appending to:

Python Grouping with setdefault()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

setdefault(word[0], []) returns the existing list for that letter, or creates an empty one, stores it and returns it. Either way, .append(word) adds to the list that lives inside the dictionary.

For heavy grouping work, collections.defaultdict does the same job even more neatly; you'll meet it in the collections lesson.

Merging: update(), | and |=

update() copies entries from another dictionary (or from key-value pairs or keyword arguments) into the current one. Existing keys are overwritten; new keys are added at the end:

Python update()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

update() changes the dictionary in place and returns None, so settings = defaults.update(...) is a classic bug: it modifies defaults and sets settings to None.

The merge operators

Python 3.9 added two operators that make merging read naturally:

  • a | b creates a new dictionary with everything from a, then everything from b. When a key appears in both, b wins.
  • a |= b updates a in place, just like a.update(b).
Python Merging with |

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use | when you want a fresh result and want to keep the originals intact; use update() or |= when you mean to change a dictionary. You may also see the older spelling {**a, **b}, which does the same as a | b; it's explained in Unpacking and Star Expressions.

Removing: pop(), popitem() and clear()

Python Removing entries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • pop(key) removes the key and returns its value; it raises KeyError for a missing key unless you give a default.
  • popitem() removes and returns the last inserted (key, value) pair, which lets you use a dictionary like a stack. It raises KeyError on an empty dictionary.
  • clear() empties the dictionary in place. Any other variable that refers to the same dictionary sees it empty too.

Views: keys(), values() and items()

These three methods don't return lists. They return view objects, which are live windows onto the dictionary. If the dictionary changes, the view shows the change:

Python Views stay in sync

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because keys() behaves like a set, you can find shared or missing keys with & and - in one step. Views can't be indexed, so wrap them in list() when you need [0] or a frozen snapshot.

Copying: copy()

Assigning a dictionary to a new name doesn't copy it; both names point at the same object. copy() creates a new dictionary with the same entries:

Python Shallow copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

copy() is shallow: the new dictionary holds the very same value objects. That's fine for strings and numbers, but mutable values such as lists are shared. When you need a fully independent copy of nested data, use copy.deepcopy(). dict(original) and original | {} also make shallow copies.

Building: dict.fromkeys()

dict.fromkeys() is a class method that creates a dictionary from a sequence of keys, all with the same value:

Python
checklist = dict.fromkeys(["passport", "tickets", "charger"], False)
# {'passport': False, 'tickets': False, 'charger': False}

unique_in_order = list(dict.fromkeys("banana"))   # ['b', 'a', 'n']

Warning: Don't pass a mutable value such as [] to fromkeys(). Every key would share the same list, so appending to one appends to all of them. Use a dictionary comprehension like {k: [] for k in keys} instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {"a": 1}.get("b", 0) return?

    get() returns the default you pass when the key is missing, and doesn't change the dictionary.
  2. 2. What is the result of {"x": 1, "y": 2} | {"y": 9}?

    The | operator merges into a new dictionary, and the right-hand side wins for keys that appear in both.
  3. 3. What does settings = defaults.update(user_prefs) leave in settings?

    update() modifies defaults in place and returns None. Use defaults | user_prefs for a new merged dictionary.
  4. 4. Which line groups words by first letter in one statement inside a loop?

    setdefault() stores the empty list when the key is missing. get() returns a new list that is never stored, and plain brackets raise KeyError for a new letter.

Summary

  • get(key, default) reads safely without changing the dictionary.
  • setdefault(key, default) reads, inserting the default first when the key is missing; great for grouping.
  • update() and |= merge in place; a | b returns a new merged dictionary where the right side wins.
  • pop() removes a key and returns its value; popitem() removes the last inserted pair; clear() empties everything.
  • keys(), values() and items() return live views; keys() and items() support set operations.
  • copy() is shallow; use copy.deepcopy() for nested data. dict.fromkeys() builds a dictionary from keys.

Next: Dictionary and Set Comprehensions, where you'll build dictionaries and sets in a single expressive line.