Python Dictionaries
Master Python dicts — create, access, update, iterate with get(), items(), keys() and examples.
What is a Dictionary?
A dictionary stores data as key-value pairs, like a real dictionary where you look up a word (key) to get its definition (value). Keys must be unique and immutable (strings or numbers). Values can be anything. Dictionaries are defined with curly braces and maintain insertion order in Python 3.7+.
person = {{ "name": "Alice", "age": 28, "city": "London" }} print(person["name"]) # direct access print(person.get("age")) # safe access print(person.get("email", "N/A")) # default if key missing
Alice 28 N/A
Always prefer .get(key, default) over direct bracket access when a key might not
exist. Direct access raises a KeyError if the key is missing; .get()
returns None or your specified default instead — no crash.
Modifying Dictionaries
d = {{"a": 1, "b": 2}} d["c"] = 3 # add new key d["a"] = 10 # update existing value print(d) del d["b"] # delete key (raises KeyError if missing) val = d.pop("a") # remove and return the value print(f"Removed: {val} | Left: {d}")
{{'a': 10, 'b': 2, 'c': 3}}
Removed: 10 | Left: {{'c': 3}}Iterating
Use .items() to loop over both keys and values at once. Use .keys() for
just keys, .values() for just values. This is the standard way to process all entries
in a dictionary.
scores = {{"Alice": 95, "Bob": 82, "Eve": 91}} for name, score in scores.items(): grade = "A" if score >= 90 else "B" print(f" {name}: {score} ({grade})") print("Top scorer:", max(scores, key=scores.get))
Alice: 95 (A) Bob: 82 (B) Eve: 91 (A) Top scorer: Alice
{{k: v*2 for k, v in d.items()}} doubles every value.🧠 Quick Check
Which method safely returns a default when a key is missing?