bhylu.com

Advertisements

Dictionary Methods

Dictionary methods support lookups, updates, views, copying, and removals. Learn their return and mutation behaviour before combining them in a chain.

Understand the idea

items gives key-value pairs, get supplies an absent-key fallback, and update changes the object in place. fromkeys creates keys sharing the same supplied value object, which is dangerous for mutable defaults. A dictionary comprehension can create an independent object per key when that is the intended model.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

groups = {name: [] for name in ["HTML", "Python"]}
groups["Python"].append("Mira")
print(groups)

Read the result

Only the Python list contains Mira. Each comprehension iteration made a separate list.

Try one change

Demonstrate the shared-default bug in a disposable example, then fix it with independent values.