Python Tutorial
Python Loop Dictionaries
A for loop over a dict yields keys. Use values() or items() for the rest.
Loop Keys, Values, Items
items() unpacks each pair.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
for x in thisdict:
print(x, thisdict[x])
for x in thisdict.values():
print(x)
for k, v in thisdict.items():
print(k, v)📘 Real-World Deep Dive
Three idiomatic ways to walk a dict — <code>for k</code>, <code>for k, v</code>, <code>for k, v in d.items()</code> — and the right way to mutate while iterating (don't). Knowing all three keeps both code and intent crisp.
Real-Life Scenario
Walk a YAML-style config to normalise keys (lowercase, hyphen-to-underscore) and produce a flat dotted-pathed dict.
Real-Life Example
raw = {
"App": {"Database": {"HOST": "db", "Port": 5432}, "DEBUG": True},
"Logging": {"Level": "INFO"},
}
def norm_key(k: str) -> str:
return k.lower().replace("-", "_")
def flatten(d, prefix=""):
out = {}
for k, v in d.items(): # standard iteration idiom
key = norm_key(k)
path = f"{prefix}.{key}" if prefix else key
if isinstance(v, dict):
out.update(flatten(v, path))
else:
out[path] = v
return out
flat = flatten(raw)
for path, value in flat.items(): # parallel unpacking
print(f"{path:<24} = {value!r}")Expected Output
app.database.host = 'db'
app.database.port = 5432
app.debug = True
logging.level = 'INFO'Common mistakes
- Iterating a dict yields *keys only*;
for v in d.values()is what you want when you don't care about keys. - Inserting into a dict while iterating it raises
RuntimeError; build a new dict or stage updates. - Tuple unpacking
for k, v in d.items()is faster than per-call indexing.
🚀 Performance & Best Practices
for k in d:is the fastest iteration form in CPython micro-benchmarks.dict.items()views share storage — safe to iterate while walking separate dicts.- For huge dicts that fit in memory but not in caches, batch the work into explicit chunks.
🧪 Try It Yourself
- Implement
nested_get(d, "a.b.c")to traverse with the same flattening. - Make
norm_keyaccept a regex. - Compare
items()withzip(keys(), values())on a 100 k dict.