Skip to content

Module 8 · Python Data Structures — topic 20 of 22

Dictionary methods

A complete reference to dictionary methods: get, keys, values, items, update, pop, popitem, setdefault, clear, copy and fromkeys, with guidance on which to use and when.

Beginner 10 min read·Lesson 123 of 306 in Python Programming

Learning objectives

  • Use every dict method appropriately
  • Copy dictionaries correctly
  • Create dictionaries with fromkeys() safely

Definition

A complete reference to dictionary methods: get, keys, values, items, update, pop, popitem, setdefault, clear, copy and fromkeys, with guidance on which to use and when.

Introduction

Dictionaries have eleven methods. You have met most of them already; this lesson collects them in one place, adds copy() and fromkeys(), and points out the traps in each.

Why it matters

A quick, reliable mental reference of what each method returns lets you choose the simplest tool for each task and avoid bugs such as accidentally sharing data between dictionaries.

Detailed explanation

MethodPurposeReturns
get(k, default)safe lookupvalue or default
keys(), values(), items()viewsview objects
update(other)merge in placeNone
pop(k, default)remove a keyits value
popitem()remove the last inserted pair(key, value)
setdefault(k, default)get or insertvalue
clear()remove everythingNone
copy()shallow copynew dict
fromkeys(keys, value)new dict with the same value for each keynew dict

copy() makes a shallow copy: a new dictionary whose values are the same objects. Changing a nested list through the copy changes the original too (deep copies come in Module 17).

dict.fromkeys(["a", "b"], 0) creates {"a": 0, "b": 0}. With a mutable default such as [], every key shares the same list, so use a comprehension instead: {k: [] for k in keys}.

popitem() removes items in last-in, first-out order and raises KeyError on an empty dictionary.

Methods that change the dictionary return None (update, clear) or the removed data (pop, popitem).

Syntax

Python
copy = original.copy()
counts = dict.fromkeys(keys, 0)
groups = {k: [] for k in keys}
last_key, last_value = d.popitem()
  • copy() is shallow.
  • fromkeys() is safe with immutable defaults.
  • Use a comprehension for mutable defaults.

Code examples

copy and fromkeys

Python
original = {"a": 1, "b": 2}
clone = original.copy()
clone["a"] = 99
print(original, clone)
print(dict.fromkeys(["x", "y", "z"], 0))
Output
{'a': 1, 'b': 2} {'a': 99, 'b': 2}
{'x': 0, 'y': 0, 'z': 0}

popitem and clear

Python
d = {"first": 1, "second": 2}
print(d.popitem())
d.clear()
print(d)
Output
('second', 2)
{}

More examples

Shared-value traps and their fixes

Python
keys = ["A", "B"]
shared = dict.fromkeys(keys, [])
shared["A"].append("Asha")
print("fromkeys with []:", shared)
separate = {k: [] for k in keys}
separate["A"].append("Asha")
print("comprehension:", separate)
config = {"name": "site", "tags": ["python"]}
shallow = config.copy()
shallow["name"] = "copy"
shallow["tags"].append("web")
print(config)
Output
fromkeys with []: {'A': ['Asha'], 'B': ['Asha']}
comprehension: {'A': ['Asha'], 'B': []}
{'name': 'site', 'tags': ['python', 'web']}

Step-by-step explanation

  • fromkeys(keys, []) uses one list object as the value for every key, so appending to A also shows under B.
  • The comprehension creates a new list for each key.
  • copy() makes a new outer dictionary, so changing name in the copy doesn’t affect config.
  • The tags list is shared between both dictionaries, so appending through the copy changes the original.

Expected output

Running “Shared-value traps and their fixes” prints exactly:

TextOutput
fromkeys with []: {'A': ['Asha'], 'B': ['Asha']}
comprehension: {'A': ['Asha'], 'B': []}
{'name': 'site', 'tags': ['python', 'web']}

Practical applications

  • Applications copy configuration dictionaries before customising them.
  • Counters are initialised with fromkeys(categories, 0).
  • Undo features use popitem() to remove the most recent entry.

Best practices

  • Use fromkeys only with immutable defaults.
  • Use copy() for a separate top-level dictionary; deepcopy for nested data.
  • Prefer get() and pop() with defaults for missing keys.

Common mistakes

Mutable default with fromkeys

Avoid

groups = dict.fromkeys(names, [])

Prefer

groups = {n: [] for n in names}

All keys share one list with fromkeys.

Copying with =

Avoid

backup = settings

Prefer

backup = settings.copy()

= only creates another name for the same dictionary.

Key takeaways

  • Dictionaries have methods for lookup, views, merging, removal and copying.
  • copy() is shallow; nested values are shared.
  • fromkeys() shares one default value across all keys.

Try it yourself

  1. 1
    Create a dictionary with every vowel as a key and 0 as the value, then count vowels in a sentence.
  2. 2
    Show that a shallow copy shares a nested list by modifying it through the copy.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic